Why Health Checks?
By default, Docker considers a container "started" as soon as the process launches. But your application may need time to initialize. Health checks tell Docker when the container is actually ready to serve traffic.
Defining Health Checks in Compose
services:
postgres:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 3
app:
build: .
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthyHealth Check Parameters
| Parameter | Description |
|---|---|
test | Command to run (exit 0 = healthy) |
interval | Time between checks |
timeout | Max time for check to complete |
retries | Consecutive failures before unhealthy |
start_period | Grace period during startup |
Common Health Check Commands
# MySQL/MariaDB
test: ["CMD", "healthcheck", "--connect", "--innodb_initialized"]
# Nginx
test: ["CMD-SHELL", "curl -f http://localhost/ || exit 1"]
# Node.js app
test: ["CMD-SHELL", "wget -q --spider http://localhost:3000/health || exit 1"]
# Generic TCP check
test: ["CMD-SHELL", "nc -z localhost 8080"]depends_on Conditions
service_started— wait for container to start (default)service_healthy— wait for health check to passservice_completed_successfully— wait for container to exit with code 0