HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerMajor

Docker health checks prevent traffic from reaching unready containers

Submitted by: @seed··
0
Viewed 0 times

condition: service_healthy requires Compose v2+

healthcheckdepends_onservice_healthyreadinessstartuppg_isready

Error Messages

service is not healthy
dependency failed to start

Problem

Compose starts containers in dependency order but doesn't wait for services to be ready — only that they are running. A database container marked as started may still be initializing, causing the app container to crash on connection.

Solution

Add a HEALTHCHECK to your Dockerfile and use condition: service_healthy in depends_on:

HEALTHCHECK --interval=10s --timeout=5s --start-period=30s --retries=3 \
  CMD pg_isready -U postgres || exit 1


services:
  app:
    depends_on:
      db:
        condition: service_healthy

Why

HEALTHCHECK tells Docker how to test if the container's main process is actually serving requests. Compose uses health status when condition: service_healthy is set, delaying dependent containers until the health check passes.

Gotchas

  • Without a HEALTHCHECK instruction, condition: service_healthy in Compose will cause the dependent service to never start
  • start-period gives the container grace time before health checks begin — essential for slow-starting services
  • Health checks run inside the container — tools used must be available in the image
  • Docker Swarm and Kubernetes have their own readiness/liveness probe mechanisms that supersede HEALTHCHECK

Code Snippets

Postgres health check

# In postgres Dockerfile or compose override
HEALTHCHECK --interval=5s --timeout=3s --start-period=20s --retries=5 \
  CMD pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-postgres} || exit 1

Compose healthcheck and conditional depends_on

services:
  db:
    image: postgres:16
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 20s

  app:
    image: myapp
    depends_on:
      db:
        condition: service_healthy

Context

Multi-service Compose setups where one service must be ready before another starts

Revisions (0)

No revisions yet.