BudiBadu Logo
Samplebadu

Docker Compose by Example: Service Dependencies

Compose Specification v2

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:alpine

Explanation

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_started waits for container to be running, default behavior
  • service_healthy waits until dependency's healthcheck passes
  • service_completed_successfully waits 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

4
depends_on: lists services that must start before web service.
12
condition: service_healthy waits for healthcheck, requires healthcheck definition.
19
test: ["CMD-SHELL", ...] exec form healthcheck, pg_isready verifies database readiness.
20
interval: 5s runs healthcheck every 5 seconds to monitor service status.