How to Use Docker Compose for Multi-Container Applications
Docker Compose lets you define and run multi-container Docker applications with a single YAML file. Instead of managing containers individually with lengthy docker run commands, Compose handles networking, volumes, and dependencies automatically. This tutorial walks you through the essential steps to get started.
Before diving in, ensure Docker Desktop or Docker Engine is installed on your system. Docker Compose comes bundled with modern Docker installations—verify with docker compose version. You’ll also need a project directory with your application code.
1. Create a docker-compose.yml File
The heart of Compose is the docker-compose.yml file. It defines your application’s services, networks, and volumes. Here’s a minimal example with a web server and a database:
- Service definition: Each service maps to a container. For example:
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "8080:80"
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: example
volumes for persistent data and networks to isolate services.2. Run and Manage Your Stack
Navigate to the directory containing your docker-compose.yml and use these fundamental commands:
- Start services:
docker compose up -d(detached mode). Compose pulls images, creates networks, and starts containers. - View logs:
docker compose logs -ffollows output from all services. - Stop & clean up:
docker compose downstops containers and removes networks. Add-vto delete volumes.
3. Scale Services and Use Environment Variables
Compose makes scaling simple. For instance, docker compose up -d --scale web=3 runs three web containers behind a common network. You can also inject variables using an .env file or the environment key inside your YAML.
- Example scaling:
docker compose up -d --scale worker=5for horizontal scaling. - Environment variables: Define them in
environment:blocks or reference${VAR}from an.envfile.
4. Use Volumes for Persistence
Without volumes, container data disappears on restart. Add a volumes block to keep database files or uploads across sessions:
- Define named volumes under
volumes:in the top level of the YAML. - Mount them inside a service:
db: volumes: - db-data:/var/lib/postgresql/data.
Docker Compose transforms complex multi-container setups into a single, repeatable process. Start with a simple docker-compose.yml, then expand with networks, volumes, and scaling to match your development or testing needs.