What Is Docker Compose?
Docker Compose lets you define and run multi-container Docker applications using a YAML file. Instead of running several docker run commands with complex flags, you describe your entire application stack in a single docker-compose.yml and start it with one command.
Your First docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:pass@db:5432/mydb
depends_on:
- db
volumes:
- .:/app
db:
image: postgres:16
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Essential Commands
# Start all services (detached)
docker compose up -d
# View running containers
docker compose ps
# View logs
docker compose logs -f web
# Stop all services
docker compose down
# Stop and remove volumes (CAUTION: deletes database data)
docker compose down -v
# Rebuild images
docker compose build --no-cache
# Run a one-off command in a service
docker compose exec web python manage.py migrate
Environment Variables
Use a .env file for secrets — it's automatically loaded by Compose:
# .env file (add to .gitignore)
POSTGRES_PASSWORD=supersecret
API_KEY=abc123
# docker-compose.yml references
services:
web:
environment:
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- API_KEY=${API_KEY}
Common Patterns
Adding Redis for Caching
redis:
image: redis:7-alpine
ports:
- "6379:6379"
Health Checks
db:
image: postgres:16
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d mydb"]
interval: 10s
timeout: 5s
retries: 5
Frequently Asked Questions
What's the difference between docker-compose and docker compose?
Docker Compose V1 was a separate Python tool (docker-compose). V2 is a Go plugin built into Docker CLI (docker compose). Use V2 — it's faster and actively maintained.
How do services communicate with each other?
Services on the same Compose network can reach each other by service name. In the example above, the web service connects to the database using db as the hostname.