✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.1.2.4 Compose API Dependencies

A focused guide to Compose API Dependencies, connecting core concepts with practical Docker and container operations.

Compose API dependencies refers to using depends_on and related Compose features to express the relationships between an API service and the other services it relies on, helping coordinate startup order and clarify the application's overall structure.

Expressing a Basic Dependency

The depends_on key declares that one service relies on another, influencing the order Compose starts services in.

services:
  api:
    build: .
    depends_on:
      - db
      - cache
  db:
    image: postgres:16
  cache:
    image: redis:7

Compose starts db and cache before starting api, reflecting the dependency relationship declared here.

Why Starting Order Alone Isn't Always Sufficient

A dependency starting doesn't necessarily mean it's immediately ready to accept connections — a database container can be running while its actual database engine is still initializing, for instance — so an API relying purely on start order might still fail its first few connection attempts.

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

This more thorough form waits not just for db to start, but for its health check to actually report healthy before starting api.

Why Application-Level Retry Logic Remains Valuable

Even with health check-aware dependencies, building reasonable retry logic into the API's own startup connection attempts provides an additional layer of resilience against transient issues that a health check might not fully capture.

for attempt in range(5):
    try:
        connect_to_database()
        break
    except ConnectionError:
        time.sleep(2)
Why Compose API Dependencies Matter

Clearly expressing an API's dependencies within the Compose file, combined with appropriately thorough readiness checks and sensible application-level retry handling, produces a more reliable startup sequence than relying on simple container start order alone.