पाठ 11 / 25

depends_on With Conditions

Wait until a dependency is healthy.

started, healthy, completed

Plain depends_on: [db] only waits until the db container has started, not until PostgreSQL accepts connections. The long form adds a condition: service_started, service_healthy (waits for the dependency's health check to pass) or service_completed_successfully (waits for a one-off job such as a migration to exit with 0). In the demo, web waits for a healthy api, which waits for a healthy db. Applications should still retry connections, because dependencies can restart later.

Start in the right order, recover from failure

Health checks and depends_on conditions make dependent services wait; restart policies recover crashes.

Three ideas: depends_on conditions, health checks, restart policies.
Figure 4.1 — Dependencies, health and restarts.

The resolved dependency chain, run

I ran this with Docker Compose v2.38.1 and jq in the demo "shop" project. docker compose config parses, interpolates, merges and validates the files without starting containers; the Docker daemon was not running, so nothing was started. web depends on api and api depends on db, both with condition service_healthy; Compose fills in required: true by default.

docker compose config --format json | jq -c ".services.web.depends_on, .services.api.depends_on"

Output:

{"api":{"condition":"service_healthy","required":true}}
{"db":{"condition":"service_healthy","required":true}}

Run migrations as a completed dependency

Add a migrate service and make the API depend on it with service_completed_successfully.

त्वरित जाँच: What does plain depends_on: [db] wait for?

  • Nothing at all
  • For the database to accept connections
  • For a health check to pass
  • Only for the db container to start, not for the database to be ready
Answer

Only for the db container to start, not for the database to be ready — Use condition: service_healthy for readiness.