TExcelTAD
Home › Docker › depends_on & Healthchecks

depends_on & Healthchecks

depends_on tells Compose that one service needs another. Compose then starts dependencies first and stops them last. With a condition, it can also wait until a dependency is actually ready, not merely started.

yaml
services:
  api:
    build: .
    depends_on:
      db:
        condition: service_healthy
      migrate:
        condition: service_completed_successfully
      cache:
        condition: service_started

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

  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: dev
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s

  cache:
    image: redis:8
Condition Compose waits until the dependency…
service_started (default for the short list form) has been started
service_healthy reports healthy from its healthcheck
service_completed_successfully has run to completion with exit code 0 (one-off jobs such as migrations)

Started is not ready

A PostgreSQL container is "started" a fraction of a second after launch, but it needs a few seconds before it accepts connections. With the plain depends_on: [db], the API often starts first, fails to connect and crashes. A healthcheck plus condition: service_healthy fixes that race.

Start order is a topological sort

Compose builds a dependency graph and starts services in an order where every service comes after everything it depends on. The algorithm is a topological sort. Step through it on the services above (an arrow means "must start before"):

The same algorithm (Kahn's algorithm, taking ready services in alphabetical order) in Python:

python · try it yourself
services = {
    "web":     ["api"],
    "api":     ["db", "migrate", "cache"],
    "migrate": ["db"],
    "db":      [],
    "cache":   [],
}

def start_order(deps):
    waiting = {name: set(d) for name, d in deps.items()}
    order = []
    ready = sorted(name for name, d in waiting.items() if not d)
    while ready:
        service = ready.pop(0)
        order.append(service)
        for name, d in waiting.items():
            if service in d:
                d.remove(service)
                if not d:
                    ready.append(name)
        ready.sort()
    if len(order) < len(deps):
        stuck = sorted(set(deps) - set(order))
        raise ValueError(f"dependency cycle detected among: {', '.join(stuck)}")
    return order

order = start_order(services)
print("start:", " -> ".join(order))
print("stop: ", " -> ".join(reversed(order)))

try:
    start_order({"a": ["b"], "b": ["c"], "c": ["a"], "d": []})
except ValueError as e:
    print("error:", e)
start: cache -> db -> migrate -> api -> web
stop:  web -> api -> migrate -> db -> cache
error: dependency cycle detected among: a, b, c

Compose refuses cyclic dependencies in the same way. It also starts independent services (here cache and db) in parallel; the order only matters along the arrows.

Simulating the wait

The model below starts the stack second by second. The database becomes healthy after its start-up, the migration job runs once the database is healthy, and the API waits for both.

python · try it yourself
db_ready_at = 6           # seconds until pg_isready succeeds
migrate_takes = 3
interval = 2              # healthcheck interval

events = []
t, db_healthy_at = 0, None
events.append((0, "db", "started"))
events.append((0, "cache", "started"))
while db_healthy_at is None:
    t += interval
    if t >= db_ready_at:
        db_healthy_at = t
        events.append((t, "db", "healthy (pg_isready ok)"))
    else:
        events.append((t, "db", "health check failed, still starting"))
events.append((db_healthy_at, "migrate", "started (db is healthy)"))
done = db_healthy_at + migrate_takes
events.append((done, "migrate", "exited with code 0"))
events.append((done, "api", "started (db healthy, migrate completed)"))

for t, service, what in events:
    print(f"t={t:>2}s  {service:<8} {what}")
t= 0s  db       started
t= 0s  cache    started
t= 2s  db       health check failed, still starting
t= 4s  db       health check failed, still starting
t= 6s  db       healthy (pg_isready ok)
t= 6s  migrate  started (db is healthy)
t= 9s  migrate  exited with code 0
t= 9s  api      started (db healthy, migrate completed)

Good healthchecks for common services

Service test
PostgreSQL ["CMD-SHELL", "pg_isready -U postgres"]
MySQL / MariaDB ["CMD", "mysqladmin", "ping", "-h", "localhost"] (MariaDB images ship healthcheck.sh --connect)
Redis ["CMD", "redis-cli", "ping"]
An HTTP API ["CMD", "wget", "-qO-", "http://localhost:8000/health"] (make sure wget/curl exist in the image)

CMD runs the program directly; CMD-SHELL runs the string through /bin/sh.

Note: depends_on only orders start-up. If the database restarts later, the API must cope with lost connections itself. Retry logic in the application is still good practice.

Restarting dependents

With restart: true under a dependency, Compose also restarts the dependent service when the dependency is restarted by a Compose operation:

yaml
depends_on:
  db:
    condition: service_healthy
    restart: true

Go deeper: depends_on & Startup Order and Healthchecks in the Docker Compose course.

Test yourself

With depends_on: [db] (short form), when does Compose start the api service?

  1. When db accepts connections
  2. As soon as the db container has been started
  3. After db exits
  4. In random order

Which condition fits a one-off database migration job that the API should wait for?

  1. service_started
  2. service_healthy
  3. service_completed_successfully
  4. service_restarted

Services: web depends on api, api depends on db. In which order does docker compose down stop them?

  1. db, api, web
  2. web, api, db
  3. api, db, web
  4. All at once, no order