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.
Direct Answer: Fix Docker Compose container is unhealthy loops by running docker inspect --format='{{json .State.Health}}' <container> to inspect the exact probe exit code. Replace missing curl binaries (exit code 127) on Alpine images with wget -qO- http://127.0.0.1:PORT/, target internal container ports rather than host ports, and add start_period: 30s.
| Health.Log Signature | Exit Code | Root Cause | Working Compose Healthcheck Fix |
|---|---|---|---|
/bin/sh: curl: not found | 127 | Minimal alpine or slim image omits curl | Use ["CMD", "wget", "-qO-", "http://127.0.0.1:80/"] or native CLI (pg_isready) |
wget: can't connect to remote host (::1): Connection refused | 1 | localhost resolves to IPv6 ::1 while app binds IPv4 0.0.0.0 | Hardcode IPv4 loopback http://127.0.0.1:PORT/ instead of localhost |
Connection refused on host port (e.g. 8080) | 1 | Probe dials published host port instead of internal container port | Probe internal container listen port (e.g. 80 or 5678) |
dependency failed to start: container is unhealthy at boot | 1 | DB migration / app init exceeds interval * retries | Add 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>. Onalpine:3.20, callingcurlin a health check failed with exit code127(/bin/sh: curl: not found), whilewgetwas already installed. Point the check at127.0.0.1on the port the process actually listens on inside the container, and give slow starters astart_periodso 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

http://127.0.0.1:80/"] transitions Status to healthy (ExitCode 0).
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).

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.

$ 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 -dprinteddependency failed to start: container gfl-hc-api is unhealthyafter 16 seconds and exited with code 1.webstayed in theCreatedstate and never ran.- For 90 seconds
RestartCountstayed at 0 and the start time didn't move, whileFailingStreakclimbed 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 .

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.

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.

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.

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.

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](https://i0.wp.com/gearflowlab.com/wp-content/uploads/2026/11/IMG_09_D_localhost_ipv6_connection_refused_vs_explicit_127001_healthy_split-3.webp?resize=1920%2C1020&ssl=1)
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.

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.

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.

- Failures inside the start period didn't count. The 20s container's
FailingStreaksat 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_periodplusinterval × retrieswas 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_periodonly pushes the verdict back. Fix the probe, then sizestart_periodto 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.

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)

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.

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

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 Image | Default Shell (/bin/sh) | curl / wget Shipped | Common Healthcheck Trap | Verified Production test Syntax |
|---|---|---|---|---|
alpine:3.20 | BusyBox ash | wget 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-alpine | BusyBox ash | Both curl & wget | Probing host port 8080 instead of container port 80 | ["CMD", "wget", "-qO-", "http://127.0.0.1:80/"] |
debian:bookworm-slim | dash (/bin/bash present) | Neither by default | Unwrapped /dev/tcp under dash (Directory nonexistent) | ["CMD-SHELL", "bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1:PORT' || exit 1"] |
node:22-alpine | BusyBox ash | wget + 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-slim | dash | python3 (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 / distroless | None (CMD-SHELL impossible) | None | Using string-form CMD-SHELL without a shell binary | Multi-stage static Go binary: ["CMD", "/healthcheck"] |

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:
- Is the probe binary actually in the running container? (
command -vworked inshon bothalpine:3.20andnginx:alpinein my test.)docker exec <container_id> sh -c 'command -v curl; command -v wget' - 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> - 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.

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.
http://127.0.0.1:PORT/) matching the socket in ss -tulpn / netstat -tlpn rather than localhost (which may resolve to ::1)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.
Run Prefilled Sizing Math & Download the 1-Page Runbook
Generate deadlock-proof Docker healthchecks plus systemd/LaunchAgent watchdogs and hardened Compose v2 YAML.