Docker Compose — Dependencies — Practice Exercises
Test your understanding of depends_on, health checks, and wait strategies.
Exercise 1: Basic depends_on
Create a stack where api depends on db. Verify db starts first.
Solution
services:
api:
image: alpine
command: sleep 3600
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
docker compose up -d
docker compose ps
db starts before api.
Exercise 2: Health Check
Add a health check to PostgreSQL and verify it shows (healthy) in docker compose ps.
Solution
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
docker compose up -d
sleep 15
docker compose ps
NAME STATUS PORTS
myapp-db-1 Up 15 seconds (healthy) 5432/tcp
Exercise 3: Wait for Healthy
Make api wait until db is healthy before starting.
Solution
services:
api:
image: alpine
command: sleep 3600
depends_on:
db:
condition: service_healthy
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
Exercise 4: Init Container
Create a migrate service that runs and exits, then api starts after it completes successfully.
Solution
services:
migrate:
image: alpine
command: sh -c "echo 'Running migrations...' && sleep 3 && echo 'Done!'"
depends_on:
db:
condition: service_healthy
api:
image: alpine
command: sleep 3600
depends_on:
migrate:
condition: service_completed_successfully
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
Exercise 5: Multi-Dependency with Health
Create a full stack: web → api → db + cache, all with health checks and condition: service_healthy.
Solution
services:
web:
image: nginx:alpine
depends_on:
api:
condition: service_healthy
api:
image: alpine
command: sh -c "while true; do echo ok | nc -l -p 3000; done"
healthcheck:
test: ["CMD-SHELL", "nc -z localhost 3000"]
interval: 5s
timeout: 3s
retries: 5
depends_on:
db:
condition: service_healthy
cache:
condition: service_healthy
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
cache:
image: redis:7
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5