`depends_on` doesn't wait for your service to be ready — here's the fix
A common Docker Compose bug: service B lists depends_on: [A], but B still crashes on
startup because A's container is running but its process (database, API, etc.) isn't
actually ready to accept connections yet. Plain depends_on only waits for the container
to start, not for the application inside it to be ready.
The fix: healthchecks + condition
Add a healthcheck to the dependency, and make the dependent service wait for it to be
healthy, not just started:
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: example
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
api:
build: ./api
depends_on:
db:
condition: service_healthy
With condition: service_healthy, Compose won't start api until db's healthcheck
passes, not merely until the container is running.
Key fields
test: the command Compose runs inside the container to decide health.CMD-SHELLruns it through a shell (supports pipes);CMDruns it directly as an exec array.interval: how often to check after the first check.timeout: how long a single check may run before it's considered failed.retries: consecutive failures before the container is markedunhealthy.start_period: a grace window at boot during which failures don't count againstretries— useful for services with slow cold starts (e.g. a JVM app or a DB running first-time migrations).
Other depends_on conditions
service_started(default): waits only for the container to start — the original, usually-insufficient behavior.service_healthy: waits for a passing healthcheck, as above.service_completed_successfully: waits for the dependency to exit with code 0 — useful for one-off init/migration containers that should run to completion before the next service starts.
Gotcha: images without a built-in healthcheck
Many official images (e.g. plain redis, nginx) don't ship a healthcheck, so
service_healthy will hang forever waiting for a check that never runs unless you define
test: yourself, as in the db example above.
Sources: Compose Specification (compose-spec.io) sections on healthcheck and
depends_on; Docker Engine documentation for HEALTHCHECK/CMD-SHELL semantics.