Compose Dependency Ordering
Intermediate10 min
Configure service startup order in Docker Compose using depends_on with health check conditions to prevent race conditions.
Prerequisites
- -Docker Compose installed
Steps
1
Define health checks for dependency services
Ensure database and cache services have health checks so dependent services know when they are ready.
$ cat <<'EOF'
services:
db:
image: postgres:16-alpine
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
EOF
2
Configure depends_on with conditions
Make the API service wait until the database is healthy before starting.
$ cat <<'EOF'
services:
api:
image: myapp:latest
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
EOF
Without the condition, depends_on only waits for the container to start, not for the service inside to be ready.
3
Verify startup order
Start the stack and verify services come up in the correct order.
$ docker compose up -d && docker compose ps
Full Script
FAQ
Discussion
Loading comments...