Docker Compose by Example: Service Dependencies
Controlling startup order with this sample code demonstrating depends_on for basic dependencies, service_healthy condition for waiting on healthchecks, service_started condition, and eliminating wait-for-it scripts.
Code
services:
web:
image: my-web-app
depends_on:
- db
- redis
worker:
image: my-worker
# Advanced syntax: wait for healthcheck
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
db:
image: postgres:15
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
redis:
image: redis:alpineExplanation
Multi-container applications often require specific startup sequences, such as web applications needing databases ready before accepting connections. The depends_on option expresses these dependencies, ensuring Docker starts services in correct topological order. By default, depends_on only waits for containers to be running, not for applications inside them to be ready.
Service dependency conditions include:
service_startedwaits for container to be running, default behaviorservice_healthywaits until dependency's healthcheck passesservice_completed_successfullywaits for one-shot containers to exit with code 0- Long syntax with conditions enables robust orchestration for slow-starting services
Using condition: service_healthy tells Compose to wait until the dependency's HEALTHCHECK passes before starting dependent services. This eliminates complex wait-for-it scripts inside containers, shifting orchestration responsibility to Docker Compose and making application code cleaner and more focused on business logic rather than infrastructure concerns.
Code Breakdown
depends_on: lists services that must start before web service.condition: service_healthy waits for healthcheck, requires healthcheck definition.test: ["CMD-SHELL", ...] exec form healthcheck, pg_isready verifies database readiness.interval: 5s runs healthcheck every 5 seconds to monitor service status.
