🎓 A1Learner
🔍
0 of 50 lessons completed

Compose Services and depends_on

depends_on sets the start order of services, so a web app starts after its database. A healthcheck proves the database is ready, and a restart policy brings a crashed service back.

Wait for the database

The web service waits until the database is healthy.

services:
  web:
    image: nginx:1.27-alpine
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: secret
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

Example

docker compose -p g6proj up -d >/dev/null
docker compose -p g6proj ps --format "{{.Name}} {{.Image}}"
docker compose -p g6proj down

Key points

  • depends_on: the list of services that must start first.
  • Start order is not readiness. A database can start and still not be ready.
  • healthcheck: a command Compose runs to test whether a service is ready.
  • condition: service_healthy waits for the healthcheck to pass.
  • restart: always brings a stopped service back up.

In this example, Compose starts the database first and waits for its healthcheck. The web service starts only after the database reports healthy. The listing shows both services, and the order proves depends_on worked.

Note

depends_on orders the start. Only a healthcheck proves readiness.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why is depends_on alone not enough for a database?