bashbeginner

Docker Health Check Patterns

Docker health check configurations for web apps, databases, and message queues with restart policies.

bash
# Dockerfile health check for a web app
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

# Alternative using curl
HEALTHCHECK --interval=15s --timeout=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1

# docker-compose.yml health checks
version: '3.8'
services:
  app:
    image: myapp:latest
    healthcheck:
      test: ['CMD', 'wget', '--spider', '-q', 'http://localhost:3000/health']
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 15s
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:16-alpine
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U appuser']
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ['CMD', 'redis-cli', 'ping']
      interval: 10s
      timeout: 3s
      retries: 3

# Check health status
# docker inspect --format='{{.State.Health.Status}}' container_name
# docker ps --filter health=unhealthy

Use Cases

  • Ensuring container readiness before traffic routing
  • Automatic container restart on failure
  • Dependency ordering in Docker Compose

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.