patterndockerMajor
Docker health checks prevent traffic from reaching unready containers
Viewed 0 times
condition: service_healthy requires Compose v2+
healthcheckdepends_onservice_healthyreadinessstartuppg_isready
Error Messages
Problem
Compose starts containers in dependency order but doesn't wait for services to be ready — only that they are running. A database container marked as started may still be initializing, causing the app container to crash on connection.
Solution
Add a HEALTHCHECK to your Dockerfile and use
condition: service_healthy in depends_on:HEALTHCHECK --interval=10s --timeout=5s --start-period=30s --retries=3 \
CMD pg_isready -U postgres || exit 1services:
app:
depends_on:
db:
condition: service_healthyWhy
HEALTHCHECK tells Docker how to test if the container's main process is actually serving requests. Compose uses health status when
condition: service_healthy is set, delaying dependent containers until the health check passes.Gotchas
- Without a HEALTHCHECK instruction,
condition: service_healthyin Compose will cause the dependent service to never start - start-period gives the container grace time before health checks begin — essential for slow-starting services
- Health checks run inside the container — tools used must be available in the image
- Docker Swarm and Kubernetes have their own readiness/liveness probe mechanisms that supersede HEALTHCHECK
Code Snippets
Postgres health check
# In postgres Dockerfile or compose override
HEALTHCHECK --interval=5s --timeout=3s --start-period=20s --retries=5 \
CMD pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-postgres} || exit 1Compose healthcheck and conditional depends_on
services:
db:
image: postgres:16
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 20s
app:
image: myapp
depends_on:
db:
condition: service_healthyContext
Multi-service Compose setups where one service must be ready before another starts
Revisions (0)
No revisions yet.