Docker Compose depends_on Doesn't Wait for Ready

· 1 min read
docker docker-compose debugging

The Problem

My app container started before the database was ready to accept connections:

services:
  app:
    depends_on:
      - db
  db:
    image: postgres:16

The app crashed immediately with “connection refused”.

The Solution

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

Why It Works

By default, depends_on only waits for the container to start, not for the service inside to be ready.

A database container starts in milliseconds. PostgreSQL inside it takes seconds to initialise. Without a healthcheck, your app tries to connect during that gap.

The condition: service_healthy option waits for the healthcheck to pass before starting dependent services.

Common healthchecks:

# PostgreSQL
test: ["CMD-SHELL", "pg_isready -U postgres"]

# MySQL
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]

# Redis
test: ["CMD", "redis-cli", "ping"]

# HTTP service
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]

This catches everyone at least once. Now you know.

Available for rescue and re-platforming work

I take over platforms that already exist and are in trouble. Node, TypeScript, React and Laravel, mostly in regulated or high-traffic environments. If something needs rescuing, re-platforming or finishing, my full history is on the CV.

Related Posts

Comments