Order and readiness
Why “started” does not mean “ready” and how to fix it.
depends_on in Compose sets the order: the api service starts after db. But “started” does not mean “ready”. The database container starts in a fraction of a second, while the database itself spends a few more seconds initialising its files and only then starts accepting connections. An application that connects immediately gets an error and may crash.
The solution is a health check. It is a command Docker runs periodically inside the container: exit code 0 means “healthy”. Combined with condition: service_healthy, Compose waits until the database is healthy and only then starts the application.
services:
db:
image: postgres:16.4
environment:
POSTGRES_PASSWORD: example
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres"]
interval: 5s
timeout: 3s
retries: 10
api:
build: .
depends_on:
db:
condition: service_healthy
pg_isready checks whether the database accepts connections. The state is shown in the STATUS column of docker compose ps: starting, healthy or unhealthy.
A health check is useful beyond start-up too. If a service hangs and stops responding, the check starts failing and the status becomes unhealthy. This shows up in monitoring and in docker ps. For your own web application the check is usually a request to a service endpoint like /health, which answers quickly and checks the essentials, such as database access.
A common mistake is to cure the start-up race with sleep 10 before starting the application. On a fast machine that wastes seconds, on a slow one it is still not enough. Another mistake is a check that itself loads the service or calls other systems: it should be cheap. And it helps when the application can retry the database connection on its own: networks and databases sometimes disappear after start-up too.
Practice
What depends_on guarantees
What does
depends_on: [db]without a condition guarantee?- That the database is ready to accept connections
- Only that the db container starts first
- That api restarts when db crashes
- That db and api use the same image
Health checks
Which statements about health checks are true? Mark all.
- Exit code 0 means a healthy service
- condition: service_healthy waits for a healthy dependency
- sleep 10 before start reliably replaces a health check
- The check should be fast and cheap
The waiting condition
Which
conditionvalue independs_onmakes Compose wait until the dependency is healthy?