PREP WITH PROOF
Menu
DOCKER & RELIABILITY / PRACTICAL GUIDE

Docker HEALTHCHECK vs Restart Policy: Why Unhealthy Stays Running

Diagnose running but unhealthy Docker containers. Separate probe status, restart policies and Compose dependency gates, with a concrete local HTTP healthcheck example.

THE QUICK ANSWER

HEALTHCHECK records a separate health signal; it does not by itself exit or restart an ordinary standalone container. Engine restart policies act on container exits and daemon lifecycle rules. Compose service_healthy gates dependency startup, while nested depends_on restart behavior concerns explicit Compose operations. Diagnose process state, probe evidence and recovery ownership separately.

Why a running, unhealthy container may never restart

Docker shows a web container as Up with an unhealthy annotation. Its restart policy is unless-stopped, but its restart count stays unchanged. That combination can be consistent: the main process is alive, while a separate health probe is failing. A restart policy for an ordinary standalone container does not turn every failed healthcheck into a process exit.

The useful diagnosis separates three questions. Is the container process running? Does the configured probe succeed? Which component is responsible for recovery? Combining them into one “up or down” label makes it easy to change the wrong setting or restart a service that cannot repair its actual dependency problem.

This guide covers Docker Engine containers and local Compose workflows. Swarm service tasks and other orchestrators have their own recovery policies. The examples below were checked against official documentation. Docker is unavailable in the authoring environment: YAML was parsed and the Python HTTP probe was tested locally, but no Docker or Compose lifecycle experiment was executed.

Read process status and health as separate signals

A configured healthcheck adds starting, healthy or unhealthy information to the container’s ordinary lifecycle status. A live process can stop serving useful requests, and a perfectly responsive application can be marked unhealthy by a badly configured probe. Neither signal alone explains the cause.

An exited container belongs to a different branch of the investigation. Inspect its exit code and application logs, then check the restart policy and whether it was manually stopped. Do not treat a missing health field as healthy: it may mean no healthcheck is configured. Capture the state before making changes so that a restart does not erase the easiest evidence.

ObservationWhat to investigateWhat it does not establish
running + healthyWhat the probe actually checksAll user operations are correct
running + unhealthyProbe command, output, target and dependenciesThe main process exited
exitedExit code, logs and restart policyThe probe caused the exit
No health informationImage/container probe configurationThe application is healthy

Collect evidence from the specific container

For a Compose project, first list all service containers and identify the relevant one. Inspect the normal state, health details and restart policy independently. Health output can reveal a missing executable, wrong URL or connection failure. Keep diagnostic output private if an application has placed credentials or sensitive responses in it.

The commands below are read-only. Run them from the directory containing the intended Compose file; the final inspect uses the ID returned for the web service. If that ID is empty, stop and identify the correct service instead of substituting an unrelated container.

docker compose ps -a
docker compose logs --tail=50 web
container_id=$(docker compose ps -a -q web)
docker inspect --type=container --format '{{json .State}}' "$container_id"
docker inspect --type=container --format '{{json .HostConfig.RestartPolicy}}' "$container_id"
docker inspect --type=container --format '{{.RestartCount}}' "$container_id"

A probe runs from the container’s point of view

The probe must use an executable that exists in the image and a target reachable from inside that container. A host’s curl command is not automatically installed in a slim application image. Likewise, localhost in a probe refers to that container, not a neighboring database or your workstation.

Check the application’s internal listening port rather than blindly copying a published host port. In the demonstration, the host mapping is 18080 to container port 8000, so the internal probe uses 127.0.0.1:8000. If the application listens on another interface, port or protocol, adjust the test to the actual deployment.

Keep the probe short, bounded and observational. Avoid a check that changes data on every run or downloads large responses. Decide whether a failure means “cannot accept useful work” or merely “an optional dependency is slow.” A probe that depends on a shared outage can mark every replica unhealthy without giving a restart any chance to fix that outage.

Create a deliberate mismatch between the process and the probe

Save this as compose.yaml in a new demonstration directory, and save the next block as health.py beside it before starting Compose. The service runs Python’s simple HTTP server on an empty /srv directory. The probe requests /ready, a file that is intentionally absent. The host port is bound to loopback; this is a local learning example, not a production web-server configuration.

The expected result is a running server with failing health probes once the failure threshold is reached. The ordinary server can answer the directory root while /ready returns an HTTP error. No auto-healing controller is included. The python:3.12-slim image tag is mutable; record the image digest if you need to reproduce a particular image build.

name: pwp-health-demo
services:
  web:
    image: python:3.12-slim
    command: ["python", "-m", "http.server", "8000", "--directory", "/srv"]
    ports: ["127.0.0.1:18080:8000"]
    volumes: ["./health.py:/health.py:ro"]
    read_only: true
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "python", "/health.py", "http://127.0.0.1:8000/ready"]
      interval: 5s
      timeout: 3s
      retries: 3
      start_period: 5s

Make the probe’s success criterion visible

The script returns zero only after an HTTP response whose final status is 200; expected network and HTTP errors return one. It disables proxy use for this direct local check and sets a two-second request timeout. It does not inspect response content or prove that a database transaction can complete. Redirect handling follows urllib’s normal opener behavior, so use the intended endpoint rather than treating a redirect as a separate readiness guarantee.

Docker’s healthcheck timeout is three seconds in this example, providing a separate outer limit. A command that exceeds that limit is a failed check. Runtime scheduling and execution duration affect observation timing; do not calculate an exact alert deadline just by multiplying interval by retries.

import sys
import urllib.error
import urllib.request

def probe(url):
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    try:
        with opener.open(url, timeout=2) as response:
            if response.status != 200:
                print('unexpected status:', response.status)
                return 1
        print('HTTP 200')
        return 0
    except (urllib.error.URLError, OSError) as error:
        print(type(error).__name__)
        return 1

if __name__ == '__main__':
    raise SystemExit(probe(sys.argv[1]))

Observe the mismatch, then correct the check

With current Docker Compose and a working Engine, validate the file with docker compose config, then start it with docker compose up -d. After probes have run, use the inspection commands above. Expect HTTP errors in the health log while the server process remains running. These are documented expected outcomes, not results measured in this publishing environment.

To test a successful HTTP probe, change the test URL from /ready to / in compose.yaml and run docker compose up -d again so the changed container configuration is applied. A root-directory response can make this demonstration healthy, but that does not make directory listing a useful readiness check for your own application. Define a real endpoint around the work your application can safely accept.

Compare container IDs when interpreting restart counts after a configuration change. A recreated container has its own identity and count; a new count is not evidence of an automatic restart of the old container. Finish the isolated example with docker compose down from this directory. No persistent volume or prune command is required.

Restart policies answer an exit question

The Engine restart-policy reference distinguishes no, on-failure, always and unless-stopped. on-failure depends on a nonzero process exit; always and unless-stopped differ in how stopped containers behave across daemon restarts. Manual stop behavior and successful-start conditions also matter. Consult those details when investigating an exited container, rather than assuming the policy is an unconditional recovery loop.

For the running/unhealthy case, the main question is who reacts to the health signal. A separately configured orchestrator or controller may take action; an ordinary Engine restart policy alone is not such a controller. Do not add several competing recovery mechanisms without deciding which owns backoff, restart limits and the decision to preserve evidence.

Restarting cannot repair every failure. A wrong probe path stays wrong after restart. A missing secret, exhausted dependency or incompatible schema may also remain broken. Use the observed failure to choose remediation instead of equating repeated process creation with restored service.

Compose startup gates are not permanent dependency supervision

Short-form depends_on establishes service order without waiting for a dependency to become healthy. The long form can use condition: service_healthy with a dependency healthcheck to gate startup. That solves an initialization race; the application still needs a policy for connections lost later.

The nested depends_on restart: true setting is another distinct control. It concerns an explicit Compose-controlled dependency restart or update, rather than automatically restarting every dependent when the runtime restarts a failed container. It is not the same setting as the service-level restart: unless-stopped in the demonstration.

After startup, handle dependency outages with deliberate application behavior: reconnect where appropriate, bound retries, surface failure to callers and avoid retry storms. A startup gate cannot make an upstream service available forever. The Kubernetes probe guide discusses a different platform’s readiness and liveness semantics; do not transplant those semantics onto a standalone Docker container.

What was actually tested for this guide

The YAML block was parsed successfully, and its healthcheck argument list was checked. That is a syntax-level check, not docker compose config validation. The exact Python probe was launched in separate local Python processes against a loopback HTTP fixture, with four scenarios: root success, missing readiness endpoint, readiness success and readiness failure again.

All eight local assertions passed: one exit-code assertion and one diagnostic-output assertion per scenario. The fixture exercises HTTP 200 and 404 handling without a container. It cannot establish Engine health transitions, restart counts, image contents, port mappings, Compose startup order or daemon behavior. Run the container exercise on your target Engine before relying on its operational result.

For a production incident, keep the same discipline: identify whether the process exited, inspect what the probe actually observed, and name the component responsible for recovery. A health signal is useful when its meaning and its consumer are explicit. That is the distinction that turns an “unhealthy but still running” surprise into a testable diagnosis.

KEEP THESE THREE THINGS

Your next steps

  1. Separate running/exited process state from starting/healthy/unhealthy probe state.
  2. Run probes using tools, ports and addresses valid inside the container.
  3. Treat restart policies, dependency startup gates and recovery controllers as separate controls.
  4. Verify operational behavior on your Engine; local HTTP and YAML tests do not replace container integration.

Sources & official resources

Linked resources checked on 2026-11-04. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →