Docker Compose file cheatsheet
Docker Compose file: Services
8 common Docker Compose file tasks.
A web app with a database
Two services: an app built from a Dockerfile, and PostgreSQL with a named volume. Keep real passwords in an env file.
services:
web:
build: .
ports:
- "8000:8000"
environment:
DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/app
depends_on:
db:
condition: service_healthy
db:
image: postgres:18
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: app
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app"]
interval: 5s
retries: 10
volumes:
pgdata:
Use an image or build one
Pull an image, or build from a folder with build arguments.
services:
api:
build:
context: ./api
dockerfile: Dockerfile
args:
NODE_ENV: production
cache:
image: redis:8
Publish ports
Map host ports to container ports. Bind to localhost to keep a port private to your machine.
ports:
- "8080:80"
- "127.0.0.1:5432:5432"
Override the command
Change the command or entrypoint that the image defines.
command: ["npm", "run", "dev"]
entrypoint: ["/entrypoint.sh"]
Add a health check
Mark a service healthy only when a command succeeds.
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 10s
timeout: 3s
retries: 5
start_period: 20s
Wait for a dependency to be healthy
Start a service only after another reports healthy.
depends_on:
db:
condition: service_healthy
Limit CPU and memory
Cap what a service can use.
deploy:
resources:
limits:
cpus: "0.5"
memory: 512M