Skip to content

DevOps Operations / Docker Compose · Step 6 of 6

Lesson: Service DependenciesSwitch
← DevOps Operations

Delivery and containers

Service Dependencies

Control start order and wait until a dependency is actually ready.

Applications often need something else to be available first, such as a database. A container that has started is not necessarily ready to answer, and Compose lets you express the difference.

Start order

The short form of depends_on lists services:

yaml
services:
  app:
    image: nginx:alpine
    depends_on:
      - db
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example

Compose starts db before app, and removes app before db when you run down. It does not wait for PostgreSQL to accept connections. Running docker compose up app also starts db; add --no-deps to skip that.

Health checks

A health check is a command Docker runs inside the container. Exit status 0 means healthy.

yaml
services:
  app:
    image: nginx:alpine
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10

Now app is started only after db reports healthy. The -h 127.0.0.1 matters: while the official image initialises a new database, its temporary server does not listen on TCP, so the check does not pass too early.

bash
docker compose ps
NAME         SERVICE   STATUS
demo-app-1   app       Up 4 seconds
demo-db-1    db        Up 10 seconds (healthy)

Output is trimmed to the useful columns.

Other conditions

condition accepts three values:

  • service_started: the dependency has been started.
  • service_healthy: its health check passes.
  • service_completed_successfully: it ran and exited with status 0.

The last one suits a one-time job, such as a database migration:

yaml
    depends_on:
      migrate:
        condition: service_completed_successfully

Still handle failures

Start-up ordering helps only at start-up. A database can restart or the network can drop later, so your application should retry its connections.

Try it

Run the health check example and watch docker compose ps while db moves from health: starting to healthy. Then change the test to ["CMD", "false"], run docker compose up -d, and read the error once the retries run out.

Check your understanding

Service Dependencies

All 4 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.