Docker Compose — Production — Practice Exercises
Practice production-ready Docker Compose configurations.
Exercise 1: Restart Policy
Configure a web server to restart automatically unless manually stopped.
Solution
services:
web:
image: nginx:alpine
restart: unless-stopped
ports:
- "80:80"
Test: docker compose kill web → it auto-restarts.
Exercise 2: Resource Limits
Set CPU and memory limits on an API service.
Solution
services:
api:
image: node:20-alpine
command: node server.js
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
reservations:
cpus: "0.1"
memory: 64M
Verify: docker stats
Exercise 3: Log Rotation
Configure JSON file logging with rotation for all services.
Solution
x-logging: &logging
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
services:
api:
<<: *logging
image: myapi:latest
db:
<<: *logging
image: postgres:16
Exercise 4: Scale a Service
Scale an API to 3 instances behind an Nginx load balancer.
Solution
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
depends_on:
- api
api:
image: myapi:latest
deploy:
replicas: 3
expose:
- "3000"
docker compose up -d
docker compose ps # Shows 3 api instances
Exercise 5: CI/CD Test Pipeline
Write a compose file for running tests in CI with proper cleanup.
Solution
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: test
healthcheck:
test: ["CMD-SHELL", "pg_isready"]
interval: 5s
retries: 5
test:
build: .
command: npm test
depends_on:
db:
condition: service_healthy
environment:
DATABASE_URL: postgres://postgres:test@db:5432/postgres
docker compose run --rm --exit-code-from test test
docker compose down -v