Toolshed

A growing library of browser tools and deep technical guides for IT professionals.

← All guides

`depends_on` doesn't wait for your service to be ready — here's the fix

2 min read

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

Other depends_on conditions

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.