How to Use depends_on in Docker Compose for Service Order
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".
services:
web:
depends_on:
- db
- redis
db:
image: postgres
redis:
image: redisExample
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.
version: '3.8' services: web: image: nginx depends_on: - db - redis db: image: postgres:15 environment: POSTGRES_PASSWORD: example redis: image: redis:7
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.
services:
web:
depends_on:
db:
condition: service_healthy
db:
image: postgres
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5Quick Reference
| Feature | Description | Example |
|---|---|---|
| Basic depends_on | Start order control only | depends_on: [db, redis] |
| depends_on with condition | Wait for health check success | depends_on: db: condition: service_healthy |
| Healthcheck | Defines how to check service readiness | healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] |
| Limitations | Does not wait for full readiness without healthchecks | Use healthchecks with condition for readiness |
Key Takeaways
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.depends_on with healthchecks and condition: service_healthy to wait for readiness.condition in depends_on for health-based waits.