0
0
DockerHow-ToBeginner · 3 min read

How to Use depends_on in Docker Compose for Service Order

In Docker Compose, use depends_on to specify that one service should start after another. It controls the startup order but does not wait for the dependent service to be fully ready. Use it by listing service names under depends_on in your docker-compose.yml file.
📐

Syntax

The depends_on key is used inside a service definition in docker-compose.yml. It lists other services that must start before this service.

  • service_name: The name of the service this one depends on.
  • List format: You can list multiple services as an array.

Note: depends_on controls start order but does not wait for services to be "ready".

yaml
services:
  web:
    depends_on:
      - db
      - redis
  db:
    image: postgres
  redis:
    image: redis
💻

Example

This example shows a web service that depends on a database and a cache service. Docker Compose will start db and redis before web, but it won't wait for them to be fully ready.

yaml
version: '3.8'
services:
  web:
    image: nginx
    depends_on:
      - db
      - redis
  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: example
  redis:
    image: redis:7
Output
Creating network "default" with the default driver Creating volume "db_data" with default driver Creating service db ... done Creating service redis ... done Creating service web ... done
⚠️

Common Pitfalls

1. depends_on does not wait for service readiness: It only controls start order, so your app might try to connect before the database is ready.

2. Using depends_on with healthchecks: In Docker Compose version 3.4 and above, you can combine depends_on with condition: service_healthy to wait for health checks.

3. Incorrect indentation or service names: YAML is sensitive to spaces, and service names must match exactly.

yaml
services:
  web:
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
📊

Quick Reference

FeatureDescriptionExample
Basic depends_onStart order control onlydepends_on: [db, redis]
depends_on with conditionWait for health check successdepends_on: db: condition: service_healthy
HealthcheckDefines how to check service readinesshealthcheck: test: ["CMD", "curl", "-f", "http://localhost"]
LimitationsDoes not wait for full readiness without healthchecksUse healthchecks with condition for readiness

Key Takeaways

Use depends_on to control the startup order of services in Docker Compose.
depends_on alone does not wait for a service to be ready, only started.
Combine depends_on with healthchecks and condition: service_healthy to wait for readiness.
Ensure correct YAML indentation and exact service names to avoid errors.
Docker Compose version 3.4+ supports condition in depends_on for health-based waits.