Home DockerDocker Compose Healthchecks: A Practical Setup Guide

Docker Compose Healthchecks: A Practical Setup Guide

by Knowledge Base Linux
docker compose healthchecks monitoring container health status

A container can be running and still be broken: the process is alive, but the web server inside has deadlocked, the database connection pool is exhausted, or the application returns errors on every request. Docker Compose healthchecks solve this blind spot by probing the application from inside the container and reporting a real health status. In this guide you will write effective healthcheck commands, tune intervals and retries, gate service startup with depends_on conditions, and debug containers stuck in the unhealthy state.

Healthchecks are cheap insurance. They turn a vague “the container is up” into a concrete signal that load balancers, orchestrators, and your own monitoring can act on. A well-tuned healthcheck catches failures minutes earlier than user complaints do, and a badly tuned one pages you at 3 a.m. for a slow startup. The difference is in the details below.

docker compose healthchecks restarting an unhealthy container automatically

How Docker Compose Healthchecks Work

A healthcheck is a command that runs periodically inside the container. If it exits with status 0, the container is healthy; any other exit code marks that probe as failed. After retries consecutive failures, Docker marks the container unhealthy. During startup, the container stays in the starting state until the first successful probe or until start_period expires.

You can inspect the status at any time with docker ps, which shows (healthy), (unhealthy), or (health: starting) next to the container, and with docker inspect, which records the last probe output. Healthchecks do not restart containers by themselves in plain Compose; they provide the signal that your restart policy, orchestrator, or monitoring uses to act.

Prerequisites

  • Docker Engine and Docker Compose v2 installed on Linux.
  • A Compose project you can modify, ideally with a web service and a database.
  • A probe tool inside your images: curl, wget, or a database client such as pg_isready or mysqladmin ping.

Step 1: Add a Basic Healthcheck to a Web Service

For a web service, probe an endpoint that proves the application is actually serving traffic, not just listening on a port:

services:
  web:
    image: nginx:1.27
    ports:
      - "8080:80"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s

The -f flag makes curl fail on HTTP error statuses, so a 500 response counts as unhealthy. Use CMD-SHELL only when you need shell features such as pipes; the exec form (CMD) is preferred because it avoids a shell process and behaves more predictably.

Step 2: Tune Intervals, Timeouts, and Retries

The four timing knobs decide whether your healthcheck is helpful or noisy:

  • interval: how often the probe runs. Thirty seconds is a good default; use 10s only for services where fast detection matters.
  • timeout: how long a single probe may run before it counts as failed. Keep it short (3-10s) so a hung probe cannot pile up.
  • retries: consecutive failures before the container is marked unhealthy. Three tolerates one transient blip without hiding real failures.
  • start_period: grace time during which failures do not count. Set this longer than your slowest cold start, especially for Java or database-backed apps.

A common mistake is setting start_period too short, so a slow-starting container is marked unhealthy before it ever had a chance. Watch docker ps during a fresh deploy and raise the value until the container never leaves the starting state prematurely.

Step 3: Gate Startup Order with depends_on Conditions

Docker Compose healthchecks become far more valuable when combined with depends_on conditions. Instead of starting the application at the same moment as the database, wait until the database is actually ready:

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

This removes an entire class of startup race conditions: no more crash loops because the app tried to migrate a database that was still initializing. Note that service_healthy requires the dependency to define a healthcheck; without one, Compose falls back to service_started.

Step 4: Write Healthchecks for Common Services

For MySQL, use the built-in ping command rather than a TCP port check, which only proves the socket is open:

test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-pexample"]

For Redis, redis-cli ping returns PONG only when the server can actually answer. For an application without curl in its image, add a tiny probe endpoint and check it with a small binary, or install curl in your own Dockerfile rather than relying on the base image to include it. Never probe a health endpoint that performs expensive work; a dedicated /healthz route that checks the database with a cheap query is the right design.

Troubleshooting Docker Compose Healthchecks

Container stuck in starting. Run docker inspect --format='{{json .State.Health}}' container_name to see the last probe output. Usually the probe tool is missing from the image or the endpoint path is wrong.

Container flaps between healthy and unhealthy. The interval is too aggressive or the probe itself is slow. Increase the timeout, raise retries to 3-5, and check whether the application is genuinely slow under load.

Healthcheck passes but the app is broken. Your probe is too shallow. A TCP connect or a static homepage check will not catch a deadlocked worker pool; probe the endpoint that exercises the real dependency chain.

depends_on seems ignored. Confirm you used the long syntax with condition: service_healthy and that the dependency container actually reaches the healthy state.

Conclusion

Well-designed Docker Compose healthchecks turn container status from a guess into a signal you can build on: faster failure detection, reliable startup ordering, and fewer 3 a.m. pages for problems a probe could have caught. Start with a real application endpoint, tune the timings against your actual startup times, and gate dependent services on health rather than mere startup. Then extend the same pattern to the rest of your stack, and read our guides on Docker Compose override files and managing Docker container logs. The official reference is Docker Compose documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.