Docker Compose
Docker Compose
Define and run multi-container applications with Docker Compose.
What is Docker Compose?
Docker Compose lets you define multi-container applications in a single docker-compose.yml file, then start everything with one command.
Why Compose?
- Replaces multiple
docker runcommands with declarative YAML - Services automatically get a shared network
- Dependency management with
depends_on - Easy environment variable management
Key Commands
bash
docker compose up # start all services
docker compose up -d # start in background
docker compose down # stop and remove containers
docker compose ps # list running services
docker compose logs -f # follow logs
docker compose exec service bash # shell into serviceExample
yaml
# docker-compose.yml
version: '3.9'
services:
# Web application
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- DATABASE_URL=postgresql://postgres:secret@db:5432/myapp
- REDIS_URL=redis://cache:6379
volumes:
- .:/app # bind mount for hot reload
- /app/node_modules # keep container node_modules
depends_on:
db:
condition: service_healthy
cache:
condition: service_started
restart: unless-stopped
# PostgreSQL database
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: myapp
POSTGRES_USER: postgres
POSTGRES_PASSWORD: secret
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
# Redis cache
cache:
image: redis:7-alpine
volumes:
- redis_data:/data
# Nginx reverse proxy
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./certs:/etc/nginx/certs
depends_on:
- app
volumes:
postgres_data:
redis_data:Try it yourself — YAML