Skip to content

Docker Compose depends_on with healthcheck: wait until a service is actually ready

Plain depends_on only waits for a container to start, not to be ready. Use docker compose depends_on condition service_healthy with a healthcheck to make the app wait for the container to be truly ready.

Plain depends_on in Docker Compose only waits for the dependency’s container to START — it says nothing about whether the process inside is ready to accept connections. So your app boots, tries to reach Postgres, and crashes because Postgres is still initializing. The fix is two parts: add a healthcheck to the dependency so Compose can tell when it is actually ready, then change the dependent’s depends_on to the long form with condition: service_healthy. Now Compose holds the app back until the database reports healthy.

What you’ll accomplish

  • Understand why plain depends_on starts your app too early.
  • Write a healthcheck on a database service that reports starting, then healthy.
  • Wire an app service to wait for condition: service_healthy before it starts.
  • Confirm ordering with docker compose ps and docker inspect.
  • Recognize the five failure modes that make service_healthy never fire — or fire too early.

Prerequisites

  • Docker Engine with Compose v2. Run it as docker compose (a subcommand), not the legacy docker-compose Python script. Check with docker compose version.
  • The long-form depends_on syntax (a map of service names to condition:) — the short-form list (depends_on: [db]) cannot express health conditions.
  • A Compose file written to the Compose Specification. The old top-level version: key is deprecated and ignored; you can delete it. Name the file compose.yaml.

How it works

Docker tracks two separate facts about a container. The first is whether it has started — the container exists and its main process has been launched. The second is whether it is healthy — a health-check command running inside the container is returning exit code 0. Plain depends_on only ever waits for “started.” A Postgres container is “started” the instant the process forks, which is seconds before it is ready to accept a single query.

A healthcheck closes that gap. Docker runs the health-check command on an interval. Each run has a timeout. While the container is inside its start_period grace window, failing probes do not count against it and the state stays starting. Once a probe succeeds, the state flips to healthy. If probes keep failing past start_period and exceed retries consecutive failures, the state becomes unhealthy. So every checked container walks through starting → healthy, or starting → unhealthy.

depends_on in long form accepts three conditions:

  • service_started — the default behavior, equivalent to plain depends_on. Waits only for the container to start.
  • service_healthy — waits until the dependency’s health check reports healthy. This is the one you want for databases, brokers, and caches.
  • service_completed_successfully — waits until the dependency exits with code 0. Use this for one-shot init or migration containers that run and finish.

Startup sequence where an app container holds until its database dependency reports healthy, versus starting immediately with plain depends_on

Step-by-step

Start from the broken version. This is what most people write first, and it looks correct:

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app

  api:
    image: myorg/api:latest
    depends_on:
      - db
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app

Bring it up and the api container often dies on first boot:

docker compose up
api-1  | Error: connection to server at "db" (172.18.0.2), port 5432 failed:
api-1  |   the database system is starting up
api-1 exited with code 1

The container started; the database inside had not finished initializing. depends_on did its only job — wait for start — and that was not enough.

Add a healthcheck to the dependency. Postgres ships with pg_isready, which returns 0 only when the server is accepting connections. That is exactly the readiness signal we need:

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 30s

interval probes every 5 seconds. timeout fails a probe that hangs longer than 3 seconds. retries: 5 means five consecutive failures after the grace window flip it to unhealthy. start_period: 30s gives Postgres up to 30 seconds to finish first-boot initialization before any failure counts.

Switch the dependent to the long form. Replace the list with a map and add the condition:

  api:
    image: myorg/api:latest
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app

Bring it up again and watch the ordering.

docker compose up
db-1   | database system is ready to accept connections
db-1   ⣿ Container compose-db-1  Healthy
api-1  | Connected to database on first attempt

Compose now blocks api from starting until db reports Healthy. The api log shows a clean first connection with no retry loop.

Check status in a second terminal. The STATUS column carries the health state:

docker compose ps
NAME             IMAGE              STATUS
compose-api-1    myorg/api:latest   Up 12 seconds
compose-db-1     postgres:16        Up 40 seconds (healthy)

(healthy) on the db row confirms the check is passing. If it read (health: starting), the app would still be waiting.

Inspect the raw health state when you need a scriptable answer rather than a formatted column:

docker inspect --format '{{.State.Health.Status}}' compose-db-1
healthy

The possible values are starting, healthy, and unhealthy. Anything other than healthy here means depends_on: condition: service_healthy is still holding your dependents back.

Validate it works

Two signals together prove the ordering is real:

  1. docker compose ps shows the dependency (healthy) and the app started only after. Run docker compose up -d then immediately docker compose ps — during the first 30 seconds you should see db as (health: starting) while api does not exist yet, then api appears once db turns (healthy).
  2. The app log shows a first-attempt connection. No lines like retrying in 2s, connection refused, or the database system is starting up. If the app connects cleanly on boot every single time across repeated docker compose down && docker compose up, ordering is doing its job.

You can also read the probe history directly:

docker inspect --format '{{range .State.Health.Log}}exit={{.ExitCode}} {{.Output}}{{end}}' compose-db-1
exit=1 ... no response ...
exit=0 ... accepting connections ...

The transition from exit=1 to exit=0 is the moment the app was allowed to start.

Troubleshooting

service_healthy never fires because the dependency has no healthcheck. Compose treats condition: service_healthy against a service with no healthcheck as an error at up time. You will see service "db" is missing a healthcheck configuration. Add the healthcheck block, or if the image defines its own HEALTHCHECK, that counts too.

start_period too short, so the container flips to unhealthy mid-startup. A cold Postgres restoring a large volume, or a JVM app with a slow warm-up, can exceed a short grace window. Probes fail, retries is hit, and the dependency goes unhealthy — which means service_healthy is never reached and the app never starts. Raise start_period to cover the real worst-case first-boot time you measure, not the happy-path time.

The healthcheck command is not in the image. Slim and distroless images frequently lack curl or wget. A test: ["CMD", "curl", ...] then fails with executable file not found, so the probe always errors and the service never turns healthy. Use a tool that ships with the image (pg_isready, redis-cli ping, mysqladmin ping), or install the tool you need in your own build.

depends_on is ignored when you name a single service. docker compose up api does start api’s declared dependencies, but docker compose run and some targeted commands can bypass the wait, and starting a service whose dependency is not in the same up invocation skips the condition entirely. If ordering matters, bring the whole project up (docker compose up) rather than one service at a time.

The healthcheck passes before the app inside is truly ready — a shallow check. pg_isready confirms the server accepts connections, but not that your specific database, user, or migration state exists. nc -z localhost 5432 is worse — it passes the moment the port is bound, which a half-initialized process can do. If your app needs the schema present, check for it: pg_isready -U app -d app at minimum, or a probe that runs a real SELECT against a required table. A deep check costs a few more lines and removes a class of intermittent boot failures.

When this is the wrong approach

depends_on conditions coordinate startup within a single Compose project on one host. They are not a substitute for orchestration. If you need rolling updates, multi-node scheduling, or automatic reschedule on node failure, that is Kubernetes territory — use readinessProbe and startupProbe on Pods instead, which express the same idea with more control.

And startup ordering is not a substitute for the app tolerating disconnects. A dependency that is healthy at boot can still restart, fail over, or drop the connection an hour later. Your app should retry connections with backoff regardless of start order. Treat service_healthy as the thing that makes the first boot clean and your logs readable — not as a guarantee the dependency is reachable forever.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.