Service Dependencies

depends_on controls startup order, and health-based conditions make a service wait until its dependency is truly ready.

Syntaxdepends_on: db: condition: service_healthy

Services often depend on one another — an API needs its database running first. The depends_on key controls startup order.

Order is not readiness

Plain depends_on waits for a container to start, but not for the app inside it to be ready. A database container can be running while Postgres itself is still initializing.

Waiting for health

To wait until a dependency is genuinely ready, combine depends_on with a healthcheck and the condition: service_healthy option.

Example

Example · yaml
services:
  api:
    build: .
    depends_on:
      db:
        condition: service_healthy

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

When to use it

  • An API service uses depends_on with a health check condition so it only starts after the database has finished its initialization.
  • A migration job declares depends_on: db to ensure the database container is at least created before the migration container runs.
  • A frontend service depends_on the API service so Compose starts the API first and the frontend does not fail on startup connecting to it.

More examples

Basic depends_on ordering

Ensures the db service is started before the api service, though it does not wait for Postgres to be ready.

Example · yaml
services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: secret

  api:
    build: .
    depends_on:
      - db
    ports:
      - "3000:3000"

Wait for service to be healthy

Uses condition: service_healthy so the api container only starts after Postgres passes its health check.

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

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

One-shot migration before app starts

Chains three services: db must be healthy before migrate runs, and api only starts after migrate exits 0.

Example · yaml
services:
  db:
    image: postgres:16-alpine
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 10

  migrate:
    build: .
    command: node scripts/migrate.js
    depends_on:
      db:
        condition: service_healthy

  api:
    build: .
    depends_on:
      migrate:
        condition: service_completed_successfully

Discussion

  • Be the first to comment on this lesson.