Opscraft
Docker Compose · Lesson 6 of 10 · 3 min read

Startup order, health and readiness

depends_on only orders starts by default

depends_on: [db]

This starts db's container before api's — but "started" isn't "ready". Postgres may still be initialising when the API tries to connect and crashes.

Conditions

depends_on:
  db:
    condition: service_healthy                 # wait for db's healthcheck to pass
    restart: true                              # restart api if db is restarted by compose
  migrate:
    condition: service_completed_successfully  # wait for a one-off job to exit 0
  cache:
    condition: service_started                 # the default

service_healthy requires the dependency to define a healthcheck. A good health check tests readiness for real (pg_isready, an HTTP /health that checks dependencies), with a start_period to give slow starters time.

docker compose up --wait waits until services are running/healthy before returning — perfect for CI.

Enlarge diagramComposedbhealthcheck: pg_isreadyapistart dbhealthcheck… not readyhealthcheck… healthynow start apiconnects first timeThe app should still retry: Compose ordering only applies at startup, and Kubernetes has no depends_on.
Figure 1. depends_on alone only waits for the container to start. With condition: service_healthy, Compose waits until the database actually answers.
Swipe sideways to see all of it, or tap to open it full screen.

Still build resilience into the app

Compose's ordering only applies at startup. If the database restarts later, or in Kubernetes where there's no depends_on, the app must retry connections with backoff. Senior answer: health-based ordering for convenience, retries for correctness.

Note that docker stack deploy (Swarm) ignores depends_on entirely, and Kubernetes has no equivalent — readiness probes and retries do that job there.