Script Valley
Docker: Complete Course
Docker ComposeLesson 4.4

Docker Compose health checks and service dependencies

healthcheck instruction, depends_on condition, service_healthy, service_started, service_completed_successfully, startup ordering

Waiting for Services to Actually Be Ready

Docker Compose health check dependency chain

depends_on alone only waits for a container to start — not for the app inside it to be ready. A database container starts in milliseconds, but Postgres takes a few seconds to accept connections. Without health checks, your API crashes on boot.

Define a Health Check

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

  api:
    build: .
    depends_on:
      db:
        condition: service_healthy

pg_isready returns exit code 0 when Postgres accepts connections. Docker checks it every 5 seconds. Once it passes 5 times, the service is marked healthy. The api service will not start until db reaches this state.

Conditions Available

service_started — container is running (default). service_healthy — healthcheck is passing. service_completed_successfully — container exited with code 0 (for migration jobs or init containers).

Up next

Scaling services and overriding Compose files for different environments

Sign in to track progress