How to add health checks in Docker Compose?

· Category: Docker

Short answer

Health checks in Docker Compose verify that a service is healthy before other services depend on it. Define them with the healthcheck key in the Compose file or the HEALTHCHECK instruction in a Dockerfile.

Steps

  1. Add a healthcheck section to the service in docker-compose.yml.
  2. Specify the test command, interval, timeout, retries, and start period.
  3. Use depends_on with condition: service_healthy for dependency ordering.

Example

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

Tips

  • Keep health check commands lightweight to avoid resource overhead.
  • Use start_period to give slow-starting services time before counting failures.
  • Check health status with docker compose ps.

Common issues

  • condition: service_healthy requires Compose file version 3.4 or higher with Docker Compose v2.
  • Misconfigured health checks can cause endless restart loops.
  • Ensure the health check command exists inside the container image.