Docker Compose is a tool for running multiple related containers as a single application. The configuration is defined in a docker-compose.yml file.
Why Use Compose
A real application consists of multiple services: a web server, a database, a cache, a task queue. Starting each one manually with docker run and dozens of flags is painful. Compose describes everything in a single file and starts it all with one command.
Minimal docker-compose.yml
version: "3.8"
services:
web:
build: .
ports:
- "8000:8000"
depends_on:
- db
environment:
DATABASE_URL: postgresql://user:pass@db:5432/mydb
db:
image: postgres:15
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Core Commands
docker compose up # start all services
docker compose up -d # in the background
docker compose up --build # rebuild images first
docker compose down # stop and remove containers
docker compose down -v # also remove volumes
docker compose ps # service status
docker compose logs # logs for all services
docker compose logs web # logs for a specific service
docker compose logs -f web # follow logs
docker compose exec web bash # get a shell inside a service
docker compose restart web # restart a service
docker compose build # rebuild images
Key Service Fields
services:
web:
image: nginx:latest # use a pre-built image
build: . # or build from a Dockerfile
ports:
- "8080:80" # host:container
volumes:
- ./html:/usr/share/nginx/html # mount a directory
environment:
- DEBUG=true # environment variables
env_file:
- .env # from a file
depends_on:
- db # startup order
restart: unless-stopped # restart policy
networks:
- backend # custom network
Networking in Compose
Services in the same docker-compose.yml can reach each other by service name automatically. From the web service you can connect to db simply by name: db:5432.
Environment Variables
# From a .env file (loaded automatically):
POSTGRES_PASSWORD=secret
# In docker-compose.yml:
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
Don’t commit .env to git — add it to .gitignore.
Restart Policies
no— do not restart (default)always— always restartunless-stopped— restart unless manually stoppedon-failure— only on error (non-zero exit code)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!