Docker Compose Healthcheck Failed: curl & Port Fixes

19 min readBy Yun Sanghun (M. Yun)

I gave a Compose service a health check that could never pass (wget to port 8080 on nginx:alpine), set restart: unless-stopped, and made a second service wait on it with condition: service_healthy. docker compose up -d exited after 16 seconds with "dependency failed to start: container gfl-hc-api is unhealthy". The second container stayed in Created. Ninety seconds later the unhealthy container was still running and its RestartCount was still 0.

Health.Log SignatureExit CodeRoot CauseWorking Compose Healthcheck Fix
/bin/sh: curl: not found127Minimal alpine or slim image omits curlUse ["CMD", "wget", "-qO-", "http://127.0.0.1:80/"] or native CLI (pg_isready)
wget: can't connect to remote host (::1): Connection refused1localhost resolves to IPv6 ::1 while app binds IPv4 0.0.0.0Hardcode IPv4 loopback http://127.0.0.1:PORT/ instead of localhost
Connection refused on host port (e.g. 8080)1Probe dials published host port instead of internal container portProbe internal container listen port (e.g. 80 or 5678)
dependency failed to start: container is unhealthy at boot1DB migration / app init exceeds interval * retriesAdd start_period: 30s so cold-boot failures do not increment FailingStreak

Translating docker run --health-cmd flags to Compose YAML or sizing PostgreSQL pools behind pg_isready? Try our Docker Run to Compose Converter and PostgreSQL & PgBouncer Memory Calculator.

Tested Environment Baseline: Windows 11 Pro (23H2) | WSL 2 Kernel 6.6.87.2-microsoft-standard-WSL2 | Official Docker Desktop (desktop-linux, Docker Engine 27.3.1, Compose v2.29.7) | Base Images: nginx:1.27-alpine, nginx:1.27 (Debian Bookworm), alpine:3.20, python:3.11-alpine, postgres:16-alpine, n8nio/n8n:1.76.1 | Empirical Execution Window: 2025-01-25 ~ 2025-01-27.

Read the health log first: Run docker inspect --format='{{json .State.Health}}' <container>. On alpine:3.20, calling curl in a health check failed with exit code 127 (/bin/sh: curl: not found), while wget was already installed. Point the check at 127.0.0.1 on the port the process actually listens on inside the container, and give slow starters a start_period so early failures don't count:

healthcheck:
  test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/"]
  interval: 10s
  timeout: 5s
  retries: 3
  start_period: 30s  # failed checks during the first 30 s do not count
Docker CLI inspecting .State.Health.Log (ExitCode 127 curl: not found) on alpine:3.20 and switching to wget on 127.0.0.1:80
Inspecting .State.Health.Log on Docker Engine 27.3.1 (Compose v2.29.7): invoking curl inside an alpine:3.20 container returns POSIX ExitCode 127 (/bin/sh: curl: not found) because only /usr/bin/wget is pre-installed, whereas switching the probe to ["CMD", "wget", "-qO-", "http://127.0.0.1:80/"] transitions Status to healthy (ExitCode 0).
Docker Compose healthcheck probe topology contrasting missing curl binaries and IPv6 ::1 localhost refusals causing unhealthy loops against native runtime probes on 127.0.0.1 with start_period
Slim/Alpine Healthcheck Execution Path: Calling curl when the image only ships BusyBox wget (or probing localhost when the daemon binds IPv4 only) traps Compose service_healthy dependencies in unhealthy; always verify the binary in-container and target 127.0.0.1 explicitly.

An unhealthy dependency: Compose exits, nothing restarts

By default, a short-form depends_on: [api] entry in docker-compose.yml uses condition: service_started. Under that default mode, Docker Compose launches the dependent container as soon as the upstream container's PID 1 process is created by the runtime, without waiting to see whether the application inside the container has bound its listening socket or passed a single health probe. When you switch the dependency definition to condition: service_healthy, Compose blocks downstream startup until Docker Engine transitions the upstream container's .State.Health.Status field from starting to healthy.

The setup, run on 2025-01-27 with Docker Engine 27.3.1 and Compose v2.29.7, uses two nginx:alpine services. api had restart: unless-stopped and a check that always fails (wget to port 8080 while nginx listens on port 80, interval: 5s, retries: 3). web had depends_on: api: condition: service_healthy. With that form of depends_on, Compose starts web only once api reports healthy (if you are migrating standalone docker run scripts into multi-service stacks, paste them into our Docker Run to Docker Compose Converter first, and note that build-time RUN npm install crashes surface differently as covered in our BuildKit npm install exit code 137 & 102 benchmark).

Split comparison of Docker Compose default depends_on (service_started) versus condition: service_healthy startup gate
Contrasting Docker Compose dependency gates on Docker Engine 27.3.1: default depends_on (service_started) launches dependent containers immediately regardless of health status, whereas condition: service_healthy blocks gfl-hc-web in the Created state and aborts docker compose up -d with exit code 1 once gfl-hc-api reaches three consecutive probe failures.

To reproduce this dependency failure deterministically, save the following two-service Compose configuration where gfl-hc-api runs standard nginx:alpine (listening on TCP port 80 inside its container network namespace) while its health check probes TCP port 8080 every 5 seconds with a 2-second timeout and 3 retries:

services:
  api:
    image: nginx:alpine
    container_name: gfl-hc-api
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/"]   # nginx listens on 80
      interval: 5s
      timeout: 2s
      retries: 3
  web:
    image: nginx:alpine
    container_name: gfl-hc-web
    depends_on:
      api:
        condition: service_healthy

Because there is no start_period defined on api, Docker Engine counts the very first failed probe at t=5s toward FailingStreak. Once the third consecutive probe fails at approximately t=16s, the container transitions from starting to unhealthy, causing docker compose up -d to abort immediately with exit code 1.

Empirical 90-second Docker Compose healthcheck failure showing gfl-hc-api unhealthy with restart_count=0 under restart: unless-stopped
docker compose up -d aborts after 16 seconds with dependency failed to start: container gfl-hc-api is unhealthy (exit 1); across 90 seconds of sampling (t+0s to t+90s), failing_streak climbs from 3 to 21 while restart_count remains 0 under restart: unless-stopped, and gfl-hc-web stays in Created.
$ docker compose up -d
   Container gfl-hc-web Created
   Container gfl-hc-api Starting
   Container gfl-hc-api Started
   Container gfl-hc-api Waiting
   Container gfl-hc-api Error dependency api failed to start
  dependency failed to start: container gfl-hc-api is unhealthy
  t+90s after compose up: status=running health=unhealthy failing_streak=21 restart_count=0 started=2025-01-27T11:21:23.553796516Z
  • docker compose up -d printed dependency failed to start: container gfl-hc-api is unhealthy after 16 seconds and exited with code 1.
  • web stayed in the Created state and never ran.
  • For 90 seconds RestartCount stayed at 0 and the start time didn't move, while FailingStreak climbed from 3 to 21. The restart policy ignored the health status. The container just kept running as (unhealthy).

In this test, restart: unless-stopped did not recover the unhealthy container because standard Docker Engine restart policies only watch whether the container's main PID 1 process exits, not whether .State.Health.Status becomes unhealthy. Not tested in this run: restart: on-failure, Docker Swarm, and external orchestration tools that restart containers based on health status.

To see why a check fails, dump the health state of the container:

docker inspect --format='{{json .State.Health}}' <container_id> | jq .
Side-by-side editor showing docker-compose.broken.yml probing port 8080 and the resulting .State.Health JSON log from Docker inspect
Inspecting the Compose service definition alongside the live .State.Health JSON object from Docker Engine 27.3.1: because nginx:alpine listens on port 80 while the healthcheck probes 127.0.0.1:8080, every 5-second check appends ExitCode 1 (Connection refused) to .State.Health.Log without triggering a container restart.

Exit code 127: the probe isn't in the image

Small base images leave a lot out to minimize image layer size and attack surface. On my PC, alpine:3.20 had /usr/bin/wget (provided by BusyBox) but no curl binary, whereas nginx:alpine had both /usr/bin/curl and /usr/bin/wget installed. When a CMD-SHELL health check calls curl -f http://localhost:80/ on an alpine:3.20 container, the POSIX shell /bin/sh cannot find the executable in $PATH and exits with code 127 and the output /bin/sh: curl: not found.

Adding || exit 1 to the end of that same command (a pattern copied across many online Compose templates) turned the recorded exit code in .State.Health.Log from 127 into generic exit code 1 while keeping the exact same /bin/sh: curl: not found output string. If you only check the numeric exit code, || exit 1 hides the missing-binary signal completely. The output text tells you more than the exit code does.

Split comparison on alpine:3.20 showing direct curl ExitCode 127 versus masked || exit 1 (ExitCode 1) and verified BusyBox wget probe
Comparing CMD-SHELL curl probes on alpine:3.20: invoking curl -fsS directly records ExitCode 127 (/bin/sh: curl: not found) in .State.Health.Log, whereas appending || exit 1 masks the exit code as 1 while leaving the identical /bin/sh: curl: not found error string in Output.

Every health check probe executes inside the target container's own mount and network namespaces, not on the Docker host. The Docker daemon spawns the configured test command inside the container at each interval, captures its standard output and standard error streams into .State.Health.Log, and evaluates the process exit code:

+-----------------------------------------------------------------------------------+
|                        Docker Daemon Host Management                              |
|                                                                                   |
|  +------------------------+                  +---------------------------------+  |
|  |  docker-compose.yml    |                  |   Container Namespace           |  |
|  |                        |                  |                                 |  |
|  |  healthcheck:          |  runs inside     |   +--------------------------+  |  |
|  |    test: ["CMD", ...]  | ---------------> |   | Executing Healthcheck    |  |  |
|  |    interval: 10s       |                  |   +-------------+------------+  |  |
|  |    start_period: 30s   |                  |                 |               |  |
|  +-----------+------------+                  +-----------------|---------------+  |
|              |                                                 |                  |
|              v                                                 v                  |
|    Health Status Evaluator                           Return Exit Code:            |
|    [ 0 = healthy           ] <---------------------- [ 0 = OK, 1 = Fail,        ] |
|    [ 1 = unhealthy         ]                         [ 127 = Command Not Found  ] |
|    [ dependent start gated ]                                                      |
+-----------------------------------------------------------------------------------+

Wrong port: same image, one healthy and one not

A wrong target port is enough on its own to lock a container in unhealthy. Two identical nginx:alpine containers on Docker Desktop for Windows 11 ran the exact same wget -qO- check with --health-interval 5s and --health-retries 2, and the port was the only difference: gfl-hc-bad probed 127.0.0.1:8080, where nothing listens inside the container namespace, and gfl-hc-good probed 127.0.0.1:80.

Two identical nginx:alpine containers comparing gfl-hc-bad probing 127.0.0.1:8080 (unhealthy) against gfl-hc-good probing 127.0.0.1:80 (healthy)
Running two identical nginx:alpine containers with --health-interval 5s and --health-retries 2: gfl-hc-good (a68c31e1afa0, probing 127.0.0.1:80) reports Up 27 seconds (healthy), while gfl-hc-bad (3191bee8c9f3, probing 127.0.0.1:8080) turns Up 31 seconds (unhealthy) with wget: can't connect to remote host (127.0.0.1): Connection refused.

This port mismatch most commonly happens when a Compose service publishes a host port mapping such as ports: ["8080:80"]. Because 8080 is the port exposed on the Windows or Linux host while the nginx worker inside the container namespace still listens exclusively on internal port 80, a health check probing 127.0.0.1:8080 receives wget: can't connect to remote host (127.0.0.1): Connection refused on every attempt. Remember that Docker executes the healthcheck.test command inside the container's own isolated network namespace, completely bypassing host-side NAT rules and published port forwards. When managing multi-container stacks, forwarding .State.Health.Log records into an observability backend such as OpenObserve (:5080) makes it easy to separate ExitCode=127 missing-binary errors from ExitCode=1 port refusals across services.

Live OpenObserve v0.14.2 Logs Explorer on port 5080 correlating container healthcheck ExitCode 127, ExitCode 1, and ExitCode 0 events
Streaming container .State.Health.Log events into OpenObserve v0.14.2 (:5080, stream docker_healthcheck_audit): centralizing probe telemetry immediately separates missing-binary failures (exit_code=127 on gfl-alpine-curl) from wrong-port and IPv6 loopback refusals (exit_code=1 on gfl-hc-bad and gfl-ipv4-app).

The loopback hostname can bite the same way even when the port number is right. Inside standard Linux containers, /etc/hosts maps localhost to both IPv4 127.0.0.1 and IPv6 ::1. If localhost resolves to ::1 first inside the container (which BusyBox wget and Alpine's musl resolver frequently attempt when querying dual-stack entries) and your application server listens only on IPv4 (0.0.0.0 or 127.0.0.1 without binding an IPv6 [::] socket), a probe to http://localhost:PORT/ fails with Connection refused against [::1]:PORT. Writing the explicit IPv4 literal 127.0.0.1 directly in the probe URL takes /etc/hosts name resolution and IPv6 loopback ordering out of the picture completely, ensuring that every health check connects straight to the IPv4 loopback interface.

Configuration comparison of container /etc/hosts dual-stack localhost (127.0.0.1 and ::1) versus explicit IPv4 127.0.0.1 CMD array healthcheck
Eliminating IPv6 loopback resolution traps in docker-compose.yml: because container /etc/hosts maps localhost to both 127.0.0.1 and ::1, specifying http://127.0.0.1:80/ in exec-array CMD form bypasses name resolution and targets the IPv4 loopback socket directly.

In addition to specifying http://127.0.0.1:PORT/, consider whether your check needs a shell at all. Docker Compose supports two syntax forms for test: the exec array form ["CMD", "wget", "-qO-", "http://127.0.0.1:80/"] and the shell string form ["CMD-SHELL", "wget -qO- http://127.0.0.1:80/ || exit 1"]. The CMD array form executes /usr/bin/wget directly via execve without spawning /bin/sh, reducing per-probe process creation overhead, avoiding shell quoting bugs, and preserving the exact numeric exit code returned by the binary. Testing an IPv4-only Python HTTP listener bound strictly to 127.0.0.1:8080 inside an Alpine container confirms why explicit IPv4 loopback is safer than localhost when writing production Compose health checks:

Split terminal verification showing wget failing against IPv6 [::1]:8080 while succeeding with HTTP 200 OK against IPv4 127.0.0.1:8080
Empirical comparison inside an Alpine container whose HTTP server binds exclusively to IPv4 (127.0.0.1:8080): probing http://[::1]:8080/ via localhost fails with Connection refused (ExitCode 1), while probing http://127.0.0.1:8080/ connects directly to the IPv4 listener and returns HTTP 200 OK.

start_period 0s vs 20s, sampled every 4 seconds

Some services need a while before they listen on their TCP socket at all: PostgreSQL initial database cluster creation, JVM runtimes running Liquibase or Flyway schema migrations, and workflow engines like n8n initializing tables. On my PC, n8n 1.76.1 logged Editor is now accessible about 4 to 12 seconds after the container started across 8 cold starts on SQLite and PostgreSQL 16. A slower host or a larger migration can take significantly longer, so time your own container boot from docker start to socket bind and set start_period comfortably above that window. With retries: 3, interval: 5s, and no start_period, a service that is still booting and migrating its database can be marked unhealthy after about 15 to 16 seconds.

Matplotlib dual-panel chart of FailingStreak trajectory (start_period 0s vs 20s) and measured container cold-start initialization times
Matplotlib telemetry analysis of Docker Engine 27.3.1 healthcheck state transitions: without start_period (left, red curve), FailingStreak reaches retries=3 at t=16s, whereas start_period: 20s (cyan curve) suppresses failure counting until t=24s and shifts the unhealthy threshold to t=36s, preventing premature failure during 4–12s n8n 1.76.1 database migrations (right).

Understanding how Docker Engine evaluates start_period prevents misconfiguring retry counts and timeout budgets. When a container starts with a health check configured, its initial health status is starting and FailingStreak is 0. If a health probe returns exit code 0 at any point during start_period, Docker immediately transitions the container to healthy without waiting for the rest of start_period to finish, unblocking any downstream Compose services waiting on condition: service_healthy. Conversely, if a probe returns a non-zero exit code while the container's elapsed uptime is still within start_period, Docker records the failure in .State.Health.Log for debugging but leaves FailingStreak at 0. Only after start_period expires do failed probes increment FailingStreak toward retries, giving slow-starting services a deterministic startup grace period.

Docker Engine 27.3.1 healthcheck state machine diagram illustrating start_period grace evaluation, FailingStreak counting, and recovery
Docker Engine 27.3.1 healthcheck state machine: probe failures during start_period leave FailingStreak at 0 and keep Status in starting, whereas any single ExitCode 0 immediately promotes the container to healthy and unblocks downstream Compose services.

I timed that exact state-machine behavior on 2025-01-27 on Docker Desktop (Windows 11, Docker Engine 27.3.1). Two identical nginx:alpine containers (sp0s and sp20s) ran the same failing check (wget -qO- 127.0.0.1:8080 || exit 1 against port 8080 where nothing was listening) with --health-interval 5s and --health-retries 3. One container had --health-start-period=0s, and the other had --health-start-period=20s. Using a shell loop in /lab/hc_start_period.sh, I sampled each container's .State.Health.Status and .State.Health.FailingStreak every 4 seconds from t=0s through t=36s. The 0s container was marked unhealthy at about 16 seconds, whereas the 20s container stayed in starting/0 through t=24s and only reached unhealthy/3 at t=36s.

Empirical 4-second sampling output from /lab/hc_start_period.sh comparing start_period 0s (unhealthy at 16s) versus 20s (unhealthy at 36s)
Sampling Status and FailingStreak every 4 seconds via /lab/hc_start_period.sh on two nginx:alpine containers with a failing port-8080 probe (interval: 5s, retries: 3): sp0s (start_period: 0s) reaches unhealthy/3 at t=16s, whereas sp20s (start_period: 20s) holds FailingStreak at 0 through t=24s before counting three post-grace failures and turning unhealthy/3 at t=36s.
  • Failures inside the start period didn't count. The 20s container's FailingStreak sat at 0 until the period ended.
  • After that it still needed three failures in a row, which took about another 15 seconds. In this run, start_period plus interval × retries was roughly how long a broken service lasted before being marked unhealthy (t=36s).
  • A check that is actually wrong ends up unhealthy either way; start_period only pushes the verdict back. Fix the probe, then size start_period to your real boot time.

start_interval: 2 seconds instead of 6

Once start_period is sized generously (for example, start_period: 30s) to protect database migrations, a new bottleneck appears if your steady-state interval is 5, 10, or 30 seconds: Docker waits for the full interval before running the first probe. Docker Engine 25.0+ (including our tested Engine 27.3.1 and Compose v2.29.7) solves this with start_interval, which polls at a faster rate (such as 1s) while the container is in the starting phase and automatically drops back to the normal interval once the container reports healthy.

Live n8n 1.76.1 workflow editor on port 5678 started behind postgres:16-alpine (condition: service_healthy, start_interval: 1s) verifying 2.04s readiness
Verifying multi-service startup orchestration in n8n 1.76.1 (:5678) on Docker Engine 27.3.1: once upstream dependency probes (pg_isready on postgres:16-alpine and wget on gfl-hc-good) pass with start_interval: 1s, Compose unblocks dependent services in 2.04 seconds and the readiness workflow executes cleanly.

With the health check pointed at the correct container port (http://127.0.0.1:80/) and start_period: 30s configured on gfl-hc-api, I timed how long docker compose up -d took to unblock and start the dependent gfl-hc-web service. Adding start_interval: 1s brought the total docker compose up -d wall-clock time down to 2 seconds (2.04s). Without start_interval (relying on the default interval: 5s cadence before the first probe ran), the exact same stack took 6 seconds (6.08s) to return. Both runs finished with api reporting healthy and web running:

    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:80/"]
      interval: 5s
      timeout: 2s
      retries: 3
      start_period: 30s
      start_interval: 1s   # check every 1 s during start_period (Docker Engine 25.0 or later)
Production Docker Compose configuration with start_period: 30s and start_interval: 1s alongside multi-stage FROM scratch static Go healthcheck
Production Docker Compose healthcheck configuration combining explicit IPv4 loopback (http://127.0.0.1:80/), a 30-second start_period grace window, and start_interval: 1s (Docker Engine 25.0+) so dependent services start within 2 seconds of socket readiness instead of waiting for the 5-second steady-state interval.

Images without wget or curl

/dev/tcp only works under bash

When neither curl nor wget is installed, many guides suggest redirecting to /dev/tcp/127.0.0.1/PORT. However, /dev/tcp/host/port is a compiled-in GNU bash feature, not a real device file in /dev. Because Docker's CMD-SHELL always invokes /bin/sh (BusyBox ash on nginx:alpine and dash on nginx:latest Debian Bookworm), an unwrapped /dev/tcp redirection fails in both images. I ran cat < /dev/null > /dev/tcp/127.0.0.1/80 || exit 1 against a running nginx in both images, and both stayed unhealthy: can't create /dev/tcp/127.0.0.1/80: nonexistent directory on Alpine, and Directory nonexistent on Debian. Wrapped in bash -c on nginx:latest, which includes /bin/bash, the same check came back healthy. nginx:alpine had no bash in my test, so stick with wget there.

Split comparison showing /dev/tcp/127.0.0.1/80 failing under BusyBox ash and Debian dash (/bin/sh) while succeeding under bash -c
Testing /dev/tcp/127.0.0.1/80 across Alpine and Debian containers on Docker Engine 27.3.1: because CMD-SHELL invokes /bin/sh (BusyBox ash on nginx:alpine and dash on Debian nginx:latest), redirecting to /dev/tcp fails with nonexistent directory unless explicitly wrapped in bash -c on an image that includes GNU bash.

If your container is based on Debian or Ubuntu (debian:bookworm-slim or ubuntu:24.04) where /bin/bash is present even when curl and wget are omitted, wrap the /dev/tcp socket redirection explicitly inside bash -c:

services:
  backend-api:
    image: custom-api:debian
    ports:
      - "8080:8080"
    healthcheck:
      # only works in images that have bash
      test: ["CMD-SHELL", "bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1:8080' || exit 1"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 20s

Runtime and static-binary probes

Distroless and scratch images have no shell (CMD-SHELL cannot run without /bin/sh), and slim language runtime images (node:22-alpine, python:3.13-slim) often omit curl. In those environments, the cleanest options are invoking the application's own language runtime in exec form (CMD, not CMD-SHELL) or copying in a tiny static binary. Because spawning an interpreter like Node.js (~68.5 ms) or Python (~42.6 ms) takes longer than BusyBox wget (~8.4 ms) or a static Go binary (~4.8 ms), give runtime probes a timeout of at least 3s to 5s.

Node.js (with fetch):

test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]

Node.js (with the http module):

healthcheck:
  test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:8080/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)}).on('error', () => process.exit(1))"]
  interval: 15s
  timeout: 5s
  retries: 3
  start_period: 25s

Python:

healthcheck:
  test: ["CMD", "python3", "-c", "import urllib.request, sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz').getcode() == 200 else 1)"]
  interval: 15s
  timeout: 5s
  retries: 3
  start_period: 25s
Matplotlib benchmark chart comparing docker compose up -d dependency wait time (2.04s vs 6.08s) and per-probe execution latency across 5 runtimes
Measured Docker Engine 27.3.1 healthcheck performance: adding start_interval: 1s reduces docker compose up -d dependency wait time from 6.08s to 2.04s (left), while compiled static Go /healthcheck (4.8 ms) and BusyBox wget (8.4 ms) execute an order of magnitude faster than spawning a Node.js V8 isolate (68.5 ms) per probe (right).

A static health check binary for scratch:

When your final stage is FROM scratch or gcr.io/distroless/static (with no /bin/sh, no wget, and no scripting runtime), a multi-stage Dockerfile can compile a tiny CGO_ENABLED=0 static Go program to perform the HTTP check and exit 0 on HTTP 200 or 1 on error:

# Build stage
FROM golang:1.23-alpine AS builder
WORKDIR /src
RUN echo 'package main; import ("net/http"; "os"); func main() { resp, err := http.Get("http://127.0.0.1:8080/health"); if err != nil || resp.StatusCode != 200 { os.Exit(1) } }' > main.go
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /healthcheck main.go

# Final scratch stage
FROM scratch
COPY --from=builder /healthcheck /healthcheck
COPY my-app /my-app
ENTRYPOINT ["/my-app"]
HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD ["/healthcheck"]

Because HEALTHCHECK ... CMD ["/healthcheck"] uses the JSON exec array form, Docker Engine executes /healthcheck directly as a child process inside the container without needing /bin/sh. Matching your probe method to the binaries shipped in your base image eliminates ExitCode=127 and shell syntax failures across all six container image families:

Container Base ImageDefault Shell (/bin/sh)curl / wget ShippedCommon Healthcheck TrapVerified Production test Syntax
alpine:3.20BusyBox ashwget only (no curl)ExitCode 127 (/bin/sh: curl: not found) or /dev/tcp failure["CMD", "wget", "-qO-", "http://127.0.0.1:PORT/"]
nginx:1.27-alpineBusyBox ashBoth curl & wgetProbing host port 8080 instead of container port 80["CMD", "wget", "-qO-", "http://127.0.0.1:80/"]
debian:bookworm-slimdash (/bin/bash present)Neither by defaultUnwrapped /dev/tcp under dash (Directory nonexistent)["CMD-SHELL", "bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1:PORT' || exit 1"]
node:22-alpineBusyBox ashwget + node (fetch)localhost resolving to IPv6 [::1] on IPv4-only listener["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
python:3.13-slimdashpython3 (urllib.request)Missing curl / wget in slim Debian layers["CMD", "python3", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz').getcode()==200 else 1)"]
FROM scratch / distrolessNone (CMD-SHELL impossible)NoneUsing string-form CMD-SHELL without a shell binaryMulti-stage static Go binary: ["CMD", "/healthcheck"]
Six-image container healthcheck compatibility matrix mapping shells, pre-installed binaries, and recommended test syntax
Container base image healthcheck compatibility matrix verified on Docker Engine 27.3.1: matching the probe mechanism (wget, bash /dev/tcp, language runtime exec-form CMD, or a static Go binary) to the binaries actually shipped in the target image prevents ExitCode 127 and shell redirection failures.

Three commands for a failing check

Whenever a container gets stuck in (health: starting) or transitions to (unhealthy), run these three commands in order before editing docker-compose.yml:

  1. Is the probe binary actually in the running container? (command -v worked in sh on both alpine:3.20 and nginx:alpine in my test.)
    docker exec <container_id> sh -c 'command -v curl; command -v wget'
  2. What did the last checks return? This lists each recorded probe result with its numeric exit code and output text:
    docker inspect --format='{{range .State.Health.Log}}{{.ExitCode}}: {{.Output}}{{end}}' <container_id>
  3. Which IP address (0.0.0.0, 127.0.0.1, or ::1) and TCP port does the server actually listen on inside the container namespace?
    docker exec -it <container_id> ss -tulpn

What I didn't test

To keep the scope of these findings explicit, I did not test Docker Swarm service health replacement, Kubernetes livenessProbe / readinessProbe / startupProbe controllers, or third-party auto-healing containers (willfarrell/autoheal) that watch the Docker socket for health_status: unhealthy events. In standalone Docker Compose (v2.29.7) on Docker Engine 27.3.1, healthcheck gates depends_on: condition: service_healthy at startup and surfaces health status in docker ps, while restart: unless-stopped remains tied to container process exit.

Three-command Docker healthcheck diagnostic runbook and end-to-end Compose service_healthy recovery verification card
Three-command healthcheck diagnostic runbook and end-to-end Compose recovery on Docker Engine 27.3.1: verifying binary presence (command -v), inspecting .State.Health.Log exit codes, and matching the listening socket (0.0.0.0:80) allows gfl-hc-api to pass its health check within 2 seconds and unblock dependent service gfl-hc-web.

Last reviewed: 2025-01-27. All empirical runs were executed on Official Docker Desktop (Windows 11 Pro 23H2, WSL 2 backend, Docker Engine 27.3.1, Compose v2.29.7) between 2025-01-25 and 2025-01-27.

Interactive Lab Verification Checklist 0 / 3 Verified
Check 1: Verify the healthcheck binary exists inside the image via docker exec <id> sh -c 'command -v curl; command -v wget' to prevent ExitCode 127
Check 2: Probe explicit IPv4 loopback (http://127.0.0.1:PORT/) matching the socket in ss -tulpn / netstat -tlpn rather than localhost (which may resolve to ::1)
Check 3: Configure start_period above your container's real initialization time and add start_interval: 1s so depends_on: service_healthy unblocks rapidly

Docker Compose Healthcheck Probes & service_healthy Q&A

Why does my container show unhealthy when the web app works fine in a browser?

Slim and Alpine base images frequently omit curl, causing CMD-SHELL curl healthchecks to exit 127 on every probe, or localhost inside the probe resolves to IPv6 ::1 while the server only listens on IPv4. Test the exact healthcheck command via docker exec and probe 127.0.0.1 explicitly.

How do I write a Docker healthcheck for distroless or minimal Node.js images without curl or wget?

Invoke the language runtime already inside the container, such as node -e with fetch('http://127.0.0.1:3000/healthz') or python3 -c with urllib.request.urlopen, exiting 0 on HTTP 200 and 1 on error.

How does start_period prevent premature unhealthy restarts during database migrations?

Setting start_period (for example 30s) gives slow-starting databases or schema migrations a grace window where failed probes do not count toward retries, while any single passing probe immediately marks the container healthy.

100% Client-Side Utilities · Printable A4 Runbook

Run Prefilled Sizing Math & Download the 1-Page Runbook

Generate deadlock-proof Docker healthchecks plus systemd/LaunchAgent watchdogs and hardened Compose v2 YAML.

Paired Prefilled Calculators & Vector PDF Checklist

Yun Sanghun (M. Yun) · Linux, Docker & AI Infrastructure Engineer