Skip to main content

Docker Compose depends_on Is Not Enough: Wait for a Healthy Database

Updated 7 min readMarkdown

Here is a bug that almost every Docker Compose user hits once. You add depends_on: [db] to your API service, run docker compose up, and the API still crashes on boot with "connection refused" to Postgres. A minute later, after a restart, everything works.

The reason is simple and it is spelled out in the Compose documentation: on startup, Compose waits until a dependency container is running, not until it is ready. Postgres can take several seconds after its process starts before it accepts connections. Plain depends_on does not cover that gap.

This post shows how to close it properly with a healthcheck and condition: service_healthy, plus the settings and pitfalls that decide whether it actually works.

The three conditions depends_on understands

The long form of depends_on accepts a condition for each dependency:

  • service_started: the default, identical to the short list syntax. Compose only waits for the container to start.
  • service_healthy: Compose waits until the dependency reports "healthy" through its healthcheck before creating the dependent service.
  • service_completed_successfully: Compose waits until the dependency runs to completion with a successful exit. This is ideal for one-off jobs such as database migrations or seeding.

service_healthy only means something if the dependency has a healthcheck. No healthcheck, no health status, nothing to wait for.

A working example: API, migrations and Postgres

services:
  db:
    image: postgres:18
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: example-only
      POSTGRES_DB: shop
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s
      start_interval: 2s

  migrate:
    build: .
    command: ["python", "manage.py", "migrate"]
    depends_on:
      db:
        condition: service_healthy

  api:
    build: .
    ports:
      - "8000:8000"
    depends_on:
      db:
        condition: service_healthy
        restart: true
      migrate:
        condition: service_completed_successfully

What happens on docker compose up:

  1. db is created first. Its healthcheck starts running.
  2. migrate waits until db is healthy, then runs and exits.
  3. api waits for both: db healthy and migrate finished successfully.

The command for migrate is just a placeholder for whatever migration tool your project uses.

Why pg_isready, and why the double dollar signs

pg_isready ships with the official Postgres image and is made for exactly this job. According to the PostgreSQL docs, it exits with 0 when the server accepts connections, 1 when the server is rejecting connections (for example during startup), 2 when there is no response, and 3 when no attempt was made because of bad parameters. A healthcheck treats exit code 0 as healthy and anything else as a failed probe, so the mapping is perfect.

The $$ is easy to miss. Compose performs variable interpolation on the YAML file itself, so a single $POSTGRES_USER would be replaced from your shell or .env file before the container ever sees it. Writing $${POSTGRES_USER} escapes the dollar sign, and the variable is expanded inside the container, where the image actually defines it. The official Compose startup order example uses this same pattern.

Also note the CMD-SHELL form. With CMD, the arguments run directly with no shell, so environment variables are not expanded at all. With CMD-SHELL (or a plain string), the command runs through /bin/sh inside the container.

Tuning the timing fields

Healthcheck timing is where most "it works on my laptop but not in CI" stories come from. The Dockerfile reference documents the defaults that Compose also uses when you leave a field out:

Field Default What it controls
interval 30s Time between checks after the start period
timeout 30s How long a single check may run before it counts as failed
start_period 0s Grace period where failures do not count toward retries
start_interval 5s Time between checks during the start period
retries 3 Consecutive failures before the container is "unhealthy"

Two details matter a lot here.

First, with the default 30 second interval, a database that is ready after 4 seconds may not be marked healthy until the next probe, so your whole stack starts slower than it needs to. That is what start_interval fixes: during the start period, Docker probes at the shorter interval, so a service can turn healthy quickly. It only applies while the start period lasts, so set start_period as well, as the example does. The Dockerfile reference notes that start_interval requires Docker Engine 25.0 or later.

Second, start_period is a grace window, not a delay. Probes still run during it, failures just are not counted. If a probe succeeds during the start period, the container is considered started and later failures count normally.

What restart: true does (and does not do)

In the example, api has restart: true on its db dependency. The Compose reference explains that this restarts the dependent service when Compose itself restarts or updates the dependency, for example after docker compose restart db. It does not apply when the container runtime restarts a crashed container on its own. It was introduced in Compose 2.17.0, so very old installs will reject it.

There is also required: false (Compose 2.20.0 and later). With it, Compose only warns when that dependency is not started or available, instead of failing. That is handy for optional sidecars such as a local mail catcher.

Use the same health signal in scripts and CI

docker compose up --wait is the CI-friendly companion to all of this. The Compose CLI reference says that with --wait, the command exits once the services are running or healthy and leaves them running. I like to pair it with --detach in pipelines, then run the test suite:

docker compose up --detach --wait --wait-timeout 120
pytest
docker compose down

If a service never becomes healthy, the command fails instead of letting your tests run against a half-started stack.

Pitfalls I would check first

  • The probe tool is not in the image. A healthcheck like curl -f http://localhost:8000/health fails forever on slim images that do not include curl. Use a tool the image has, or add a tiny check script.
  • Checking the wrong thing. A TCP port check can pass before the app has run its own startup work. Prefer an endpoint or command that proves the service is actually usable.
  • Expensive probes. The probe runs every interval for the life of the container. Keep it cheap.
  • Debugging blind. The probe's output is stored in the health status. docker inspect on the container shows the recent results, which usually explains an "unhealthy" state in seconds.
  • Treating startup order as resilience. Healthchecks fix the boot sequence. Your app should still retry connections, because databases restart in production too.

The short version

Plain depends_on waits for "running". Add a real healthcheck to the dependency, use condition: service_healthy for long-running services and service_completed_successfully for one-off jobs, shorten start_interval so healthy services are detected quickly, and use docker compose up --wait in CI.

If you want a structured path from single containers to multi-service stacks like this one, the Tutorials Mania live Docker course with hands-on Compose labs walks through it step by step, and it leads naturally into Kubernetes concepts that interviewers ask about such as readiness probes.

Written by the editorial team at Tutorials Mania.

About the author

  • Tutorials Mania (https://tutorialsmania.com) is a free learning platform with step-by-step tutorials, interview questions and practical guides on AI, cloud, cybersecurity, programming, SEO and digital marketing. We also built a free, no-sign-up resume builder: https://tutorialsmania.com/resume-builder/

No comments yet. Be the first to comment.