Skip to content

Docker Compose Healthcheck Explained

Add healthchecks in Docker Compose: the test command, interval, timeout, retries, start_period, and using depends_on condition: service_healthy correctly.

SDSysadmin Desk November 28, 2026 8 min read
Photographic illustration for Docker Compose Healthcheck Explained: server racks with glowing container blocks

A container can be “running” and completely useless. The process started, so Docker considers it up — but the database is still replaying its write-ahead log, the web server is still loading config, and any service that connects right now gets a connection refused. Plain depends_on doesn’t help, because it only waits for the container to start, not for the app inside to be ready.

Healthchecks close that gap. You give Compose a command that proves the app is actually working, and Compose runs it on a schedule to track the container’s health. Dependent services can then wait for healthy instead of guessing with sleep, and you get a real signal for monitoring and restarts.

This guide covers the healthcheck fields and what each one does, the depends_on condition that makes startup ordering reliable, and how to debug a check that’s stuck unhealthy.

Running is not the same as ready

When Compose starts a stack, it brings up containers and, with a basic depends_on, starts dependents as soon as the dependency’s container is running. The problem: a Postgres container reports “running” the instant the process launches, but it isn’t accepting connections until initialization finishes — sometimes several seconds later. Your app starts, tries to connect, and crashes.

The usual bad workaround is a sleep 10 in the app’s entrypoint. It’s fragile: too short and you still race the database, too long and every startup wastes time. A healthcheck replaces the guess with a real readiness signal.

Container health states

starting Initial state. During start_period, failing checks don't count yet.
healthy The test command exited 0 — the app is responding as expected.
unhealthy The test failed enough consecutive times to cross the retries threshold.
(none) No healthcheck defined; Docker only knows running vs stopped.

You can see the state any time:

docker ps          # the STATUS column shows (healthy) / (unhealthy)
docker inspect --format '{{.State.Health.Status}}' <container>

Anatomy of a healthcheck

A healthcheck in Compose is a block of fields under a service. Here’s a complete one for a Postgres database:

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-me
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

Each field has a specific job:

Healthcheck fields

test The command that decides health. Exit 0 = healthy, non-zero = failing.
interval How often to run the test once the container is up (default 30s).
timeout How long a single test may run before it's treated as a failure.
retries Consecutive failures needed to flip the status to unhealthy.
start_period Grace window at startup; failures here don't count toward retries.
start_interval Optional faster interval during start_period (newer Docker).

So this Postgres check runs pg_isready every 10 seconds, allows 30 seconds of grace at boot, and only marks the container unhealthy after 5 consecutive real failures. That tolerance matters — a single slow response during a backup shouldn’t declare the database dead.

A web service usually probes an HTTP endpoint. Prefer a dedicated /health route if the app has one:

  web:
    image: myapp:latest
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 15s
      timeout: 5s
      retries: 3
      start_period: 20s

The -f flag makes curl exit non-zero on HTTP errors like 500, so a broken app reports unhealthy instead of passing on a returned error page.

start_period: the field people forget

start_period is the difference between a healthcheck that works and one that kills your container during boot. Apps that take time to initialize — databases, JVM services, anything loading a large config — will fail their first few checks simply because they aren’t up yet.

Without a grace window, those early failures count toward retries and the container gets marked unhealthy before it ever finishes starting. start_period carves out a window where failing checks keep the container in starting rather than penalizing it. Once the app passes a check, the container goes healthy and normal interval/retries rules take over.

Wiring depends_on to wait for healthy

This is where healthchecks pay off. The long-form depends_on lets a service wait until its dependency is healthy, not merely started:

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-me
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

  app:
    image: myapp:latest
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://postgres:change-me@db:5432/app

Now Compose won’t start app until db reports healthy. The race is gone — no sleep, no retry-on-connect hacks in the app. The conditions you can use:

depends_on conditions

service_started Default. Waits only for the container to start. No readiness guarantee.
service_healthy Waits until the dependency's healthcheck reports healthy.
service_completed_successfully Waits for the dependency to exit 0 — good for one-shot init/migration jobs.

service_completed_successfully is handy for an init container that runs database migrations and exits — the app waits for the migration job to finish cleanly before starting. The Compose file line-by-line guide covers how depends_on fits with the rest of a service definition.

Make sure the test command exists in the image

A healthcheck runs inside the container, so the command must be available there. This catches people out constantly: a slim or distroless image often has no curl and no wget, so a curl-based check fails not because the app is down but because the binary doesn’t exist.

Check what’s actually in the image, or use what’s already there:

# Does the image even have curl?
docker run --rm myapp:latest which curl || echo "no curl in image"

If curl is missing, options include installing it in the Dockerfile, using wget if present, or probing with whatever the runtime provides. Many language images can run a tiny inline check — for example, Python or Node can open a socket without any extra package:

    # No curl needed — use the language runtime already in the image
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8080/health').status==200 else 1)"]
      interval: 15s
      timeout: 5s
      retries: 3
      start_period: 20s

Debugging an always-unhealthy check

When a container won’t go healthy, work through this short list before changing intervals at random:

Why a healthcheck stays unhealthy

  • Run the test by hand: docker exec — read the real error
  • Confirm the command exists in the image (curl/wget may be missing)
  • Check the port and path — is the app really on that port inside the container?
  • Verify the app binds 0.0.0.0, not 127.0.0.1, inside the container
  • Make sure start_period covers the app's true boot time
  • Inspect health log: docker inspect --format '{{json .State.Health}}'

The single most useful step is running the test command yourself inside the container:

docker exec -it <container> curl -f http://localhost:8080/health

If that fails, you’ll see the actual reason — connection refused, 404, missing binary — instead of just unhealthy. The health log keeps the last several check outputs, which is the next place to look:

docker inspect --format '{{json .State.Health}}' <container>

That 127.0.0.1 item is worth repeating because it overlaps with the most common port problem: if the app inside binds to localhost only, even a correct healthcheck can’t reach it. The same root cause shows up when ports don’t work as expected — see Docker port mapping explained for the 0.0.0.0 vs 127.0.0.1 distinction inside containers.

Overriding or disabling an image’s healthcheck

If an image ships its own HEALTHCHECK and it doesn’t fit your environment, the Compose healthcheck block overrides it. To turn one off entirely:

    healthcheck:
      test: ["NONE"]

That’s occasionally necessary when a baked-in check is too aggressive, probes something unavailable in your setup, or interferes with your own monitoring. Most of the time, though, defining your own check with a sensible start_period is the better move than disabling it.

Wrapping up

A healthcheck turns “the container is running” into “the app is actually ready,” and that distinction fixes a whole class of startup races. Give Compose a test command that proves real readiness, tune interval, timeout, and retries for sensible tolerance, and set start_period to cover the app’s true boot time. Then let dependents wait on condition: service_healthy instead of sleeping and hoping.

Two things to remember: the test command has to exist inside the image, and a healthcheck reports status but won’t restart anything on its own — pair it with a restart policy for that. Get those right and your stack comes up in the correct order every time. For more, see the Compose file explained line by line, restart policies explained, and the Docker & Containers guides.

Frequently asked questions

What does a healthcheck do in Docker Compose?

It runs a command inside the container at intervals to decide whether the service is actually working, not just running. The result sets the container's health status to starting, healthy, or unhealthy. Other services can wait for healthy before starting, and orchestrators can act on unhealthy.

How does depends_on use a healthcheck?

With the long form depends_on: : condition: service_healthy, Compose waits until the dependency reports healthy before starting the dependent service. Plain depends_on only waits for the container to start, not for the app inside to be ready — which is why apps often fail to reach a database that's still initializing.

What's the difference between interval and start_period?

interval is how often the check runs once the container is up. start_period is an initial grace window during which failing checks don't count against retries, giving slow-starting apps time to boot. Failures during start_period don't mark the container unhealthy; they just keep it in starting.

Why is my healthcheck always unhealthy?

Common causes: the test command isn't installed in the image (curl or wget missing), it probes the wrong port or path, the app binds 127.0.0.1 inside so the check can't reach it, or start_period is too short for the app's boot time. Run the test command manually with docker exec to see the real error.

Does an unhealthy container restart automatically?

Not on its own. A healthcheck only sets status; it doesn't restart anything by itself in plain Compose. You need a restart policy, or an orchestrator like Swarm/Kubernetes, to act on the unhealthy state. Combining a healthcheck with restart: unless-stopped is a common pattern.

Can I set a healthcheck without editing the image?

Yes. Define healthcheck directly in the Compose service. It overrides any HEALTHCHECK baked into the image. You can also disable an image's healthcheck with test: ["NONE"] if it's misbehaving or too aggressive for your environment.

Sources & further reading

Official vendor documentation referenced while writing this guide.

SD

Sysadmin Desk

Infrastructure & Cloud

Hands-on guidance for infrastructure, virtualization, and containers — Hyper-V, VMware, Docker, and the day-to-day operations work that keeps environments running.

MCSA Guru provides independent, educational IT guidance. Microsoft, Windows, Windows Server, Microsoft 365, Exchange, and Microsoft Teams are trademarks of Microsoft Corporation; Docker is a trademark of Docker, Inc. MCSA Guru is not affiliated with or endorsed by Microsoft or Docker. Always test changes in a safe environment before applying them in production.

Related guides

Fixing something right now?

Jump straight into the guide library or search for the exact error or task you are dealing with.