C.W.K.
Stream
Lesson 03 of 04 · published

depends_on + healthchecks — Wait Until Actually Ready

~14 min · compose, production

Level 0Container Curious
0 XP0/36 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

The classic startup race

Your API depends on Postgres. Compose starts both. The API container is up in 200ms. Postgres takes 4 seconds to be ready for connections. The API tries to connect, fails, exits. docker compose up reports the API died. The fix is not retry-loops — it's depends_on: condition: service_healthy.

service_healthy waits for HEALTHCHECK to pass

You add a HEALTHCHECK to the dependency (in the compose file or the Dockerfile). The dependent service waits until that check goes green before starting.

Code

API waits for DB to be actually ready·yaml
services:
  api:
    build: ./api
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

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

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 5

External links

Exercise

Take an existing compose stack (or build a minimal one with API + Postgres). Confirm the race condition: remove HEALTHCHECK, add a 5-second sleep to your DB startup, watch the API fail. Then add HEALTHCHECK + condition: service_healthy and confirm the API now waits patiently.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.