Containers and Kubernetes · Intermediate · 13 min
Add a Docker HEALTHCHECK that works without curl
By Padding · Updated 18 Nov 2026
node:26 (Debian) · Node.js 26.13 · Docker Engine 29.10
You will write a small health-check script in Node.js that needs no curl, prove it exits 0 when the app is healthy and 1 when it fails, hangs or is down, and wire it into a Dockerfile HEALTHCHECK with timings you can explain.
On this page
A Docker HEALTHCHECK runs a command inside the container on a schedule and marks the container healthy or unhealthy from its exit code. The usual example is curl -f http://localhost/ || exit 1. It fails the moment you move to a smaller image: the official node:26-slim image installs curl and wget to download Node.js and then removes them, and distroless images have no curl, no wget and no shell at all.
The fix is to write the check in the runtime the image already has. A Node.js image always has node, and Node.js 26 has fetch built in, so a dozen lines of JavaScript do the job with no extra packages and nothing added to the image.
You will build a tiny web app with a /healthz route, write healthcheck.mjs, prove it gives the right exit code when the app is fine, returning errors, hanging and stopped, and then add it to a Dockerfile. The last step covers two facts people often miss: Docker does not restart an unhealthy container on its own, and Kubernetes ignores HEALTHCHECK completely.
Step 1 · Create an app with a health route
Make a throwaway project folder:
mkdir -p ~/healthcheck-demo
cd ~/healthcheck-demoWrite the app. It answers / with a greeting and /healthz with a short JSON status. So that you can practise failures without breaking anything real, two marker files change how /healthz behaves: if /tmp/fail-health exists it answers HTTP 503, and if /tmp/hang-health exists it never answers at all. In your own app, /healthz would check what the app needs to work, such as a database connection:
cat > server.mjs <<'JS'
import { createServer } from 'node:http'
import { existsSync } from 'node:fs'
const port = Number(process.env.PORT ?? 3000)
const server = createServer((req, res) => {
if (req.url === '/healthz') {
// Practice switches. Replace these with real checks in your own app.
if (existsSync('/tmp/hang-health')) return
const failing = existsSync('/tmp/fail-health')
res.writeHead(failing ? 503 : 200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ status: failing ? 'failing' : 'ok' }))
return
}
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('Hello from the health-check demo\n')
})
server.listen(port, () => console.log(`Listening on port ${port}`))
process.on('SIGTERM', () => server.close(() => process.exit(0)))
JSThe app uses only Node.js built-in modules, so there is no npm install. Start it in your second terminal, from the same folder, and leave it running:
cd ~/healthcheck-demo
node server.mjsCheck it worked
The second terminal prints Listening on port 3000. In your first terminal, ask for the health route with Node.js itself:
node -e "fetch('http://127.0.0.1:3000/healthz').then(r => r.text()).then(console.log)"The reply is {"status":"ok"}.
Step 2 · Write the health-check script
Docker reads only the exit code of a health check: 0 means healthy and 1 means unhealthy. Code 2 is reserved, so never use it, and never let the script crash with some other code. Anything the script prints is stored with the result, up to the first 4096 bytes, so keep messages to one short line.
Create healthcheck.mjs. The .mjs extension makes it an ES module, which allows await at the top level:
cat > healthcheck.mjs <<'JS'
// Exit 0 when the app answers /healthz with a 2xx status, 1 otherwise.
const url = process.env.HEALTH_URL ?? 'http://127.0.0.1:3000/healthz'
const timeoutMs = Number(process.env.HEALTH_TIMEOUT_MS ?? 2000)
try {
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })
if (res.ok) {
console.log(`healthy: HTTP ${res.status}`)
process.exit(0)
}
console.error(`unhealthy: HTTP ${res.status}`)
process.exit(1)
} catch (err) {
const reason =
err.name === 'TimeoutError' ? `no answer in ${timeoutMs} ms` : (err.cause?.code ?? err.message)
console.error(`unhealthy: ${reason}`)
process.exit(1)
}
JSThree choices in it matter:
127.0.0.1, notlocalhost. Inside a container,localhostcan resolve to the IPv6 address::1first. If the app listens only on IPv4, the check fails while the app is fine.- Its own timeout.
AbortSignal.timeoutstops the request after two seconds and prints a clear reason. Without it, a hung app makes the script wait until Docker kills it, and the stored result says nothing useful. - Every failure becomes exit 1. A refused connection, a timeout and a 5xx status all go through the same two exits, so Docker never sees an unexpected code.
Check it worked
With the app running, run the script and print its exit code:
node healthcheck.mjs
echo "exit code $?"The output is healthy: HTTP 200 and then exit code 0.
Step 3 · Prove the failure cases
A health check that never fails is worse than none, because it tells you everything is fine. Make the app return errors, then hang, then disappear, and check each time that the script exits with 1. The || echo part prints the code without stopping your shell.
Turn on the 503 switch:
touch /tmp/fail-health
node healthcheck.mjs || echo "exit code $?"The output is unhealthy: HTTP 503 and exit code 1.
Now swap it for the hang switch. The app accepts the connection and never replies:
rm /tmp/fail-health
touch /tmp/hang-health
node healthcheck.mjs || echo "exit code $?"After about two seconds the output is unhealthy: no answer in 2000 ms and exit code 1.
Remove the switch, then stop the app with Ctrl+C in the second terminal, and run the script once more:
rm /tmp/hang-healthnode healthcheck.mjs || echo "exit code $?"Check it worked
The output is something like unhealthy: ECONNREFUSED and exit code 1. You have now seen exit 0 for a healthy app and exit 1 for an error status, a hang and a stopped app, which are the four cases Docker needs to tell apart.
Step 4 · Add HEALTHCHECK to the Dockerfile
Write a Dockerfile based on the slim image, which has no curl:
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY server.mjs healthcheck.mjs ./
ENV NODE_ENV=production
EXPOSE 3000
USER node
HEALTHCHECK --interval=15s --timeout=5s --start-period=30s --start-interval=2s --retries=3 \
CMD ["node", "healthcheck.mjs"]
CMD ["node", "server.mjs"]
DOCKERWhat each option does, with Docker's default in brackets:
--interval=15s(30s): time between checks once the container has started.--timeout=5s(30s): Docker kills a check that runs longer and counts it as a failure. Keep it above the script's own two-second timeout, so the script reports the reason itself.--start-period=30s(0s): a grace window for slow starts. Failures inside it do not count towards--retries. The first success ends it early.--start-interval=2s(5s): how often to check during the start period, so a fast-starting app is marked healthy in seconds, not after a full interval. It needs Docker Engine 25.0 or later.--retries=3(3): consecutive failures before the status becomesunhealthy.
With these numbers a container that stops answering is marked unhealthy after three failed checks, so roughly 30 to 45 seconds after the problem starts (a little longer when the app hangs, because each check waits for its own timeout). Shorter intervals notice sooner but start a new Node.js process each time, which costs CPU and memory. On a small 1 GB server, the kind many teams in Nigeria, Kenya and elsewhere start on to keep hosting costs down, 15 to 30 seconds is a sensible range.
Use the exec form, CMD ["node", "healthcheck.mjs"], as shown. The shell form (CMD node healthcheck.mjs) runs through /bin/sh -c, which distroless images do not have, so the check would fail on every run there. In a distroless Node.js image, use the full path to node given in that image's documentation.
A Dockerfile has one effective HEALTHCHECK: if there are several, the last one wins. A base image may ship its own; HEALTHCHECK NONE turns an inherited check off.
Check it worked
grep -A1 '^HEALTHCHECK' DockerfileThe output shows the HEALTHCHECK line with its five options and the CMD ["node", "healthcheck.mjs"] line under it.
Step 5 · Build, run and read the health status
Build the image and start a container, publishing the port on your own machine only:
docker build -t healthcheck-demo:1 .
docker run -d --name hc-demo -p 127.0.0.1:3000:3000 healthcheck-demo:1
docker ps --filter name=hc-demoFor the first few seconds the STATUS column shows Up 3 seconds (health: starting). Within the start period it changes to (healthy). Read the full record:
docker inspect --format '{{json .State.Health}}' hc-demoThe output is one line of JSON, something like {"Status":"healthy","FailingStreak":0,"Log":[{"Start":"...","End":"...","ExitCode":0,"Output":"healthy: HTTP 200\n"}]}. Log holds the last few results, each with its exit code and the line the script printed.
Now break it from inside the container. The app user can write to /tmp:
docker exec hc-demo touch /tmp/fail-healthCheck it worked
Wait about a minute and run docker ps --filter name=hc-demo again. STATUS reads (unhealthy), and docker inspect --format '{{json .State.Health}}' hc-demo shows "FailingStreak":3 or more, with unhealthy: HTTP 503 in each Output. Remove the switch with docker exec hc-demo rm /tmp/fail-health and, after the next check, the status returns to (healthy).
Step 6 · Decide what happens when it turns unhealthy
Look at docker ps once more while the container is unhealthy: it is still Up. This is the fact most people miss. Docker's restart policies (--restart on-failure, always, unless-stopped) react when the main process exits, not to health status. An unhealthy container keeps running and keeps receiving traffic until something else acts on it.
Things that do act on it:
- Docker Compose can hold back a service until another one is healthy with
depends_onandcondition: service_healthy. That is about start order, not recovery. - Your own tooling can watch for changes with
docker events --filter event=health_statusand restart the container or alert someone. - The app itself can exit when it knows it is broken beyond repair. Then a restart policy does its job.
Kubernetes goes further: it ignores the HEALTHCHECK in your image completely. It uses startup, readiness and liveness probes declared on the Pod. You can point an exec probe at the same node healthcheck.mjs, but an httpGet probe on /healthz is lighter, because the kubelet sends the request without starting a process. Keep the HEALTHCHECK for plain Docker and Compose, and write probes for Kubernetes.
Clean up the container, the image and the demo folder:
docker rm -f hc-demo
docker rmi healthcheck-demo:1
cd ~
rm -rf ~/healthcheck-demoCheck it worked
docker ps -a --filter name=hc-demo lists no containers, docker images healthcheck-demo lists no images, and ls ~/healthcheck-demo reports that the folder does not exist.
Next steps
- Make a web app wait for a healthy database in Compose: /tutorials/docker-compose-app-with-postgres
- Write startup, readiness and liveness probes for Kubernetes: /tutorials/keep-snip-healthy-with-probes-and-graceful-shutdown
- Go back over the basics of a Node.js Dockerfile: /tutorials/write-a-dockerfile-for-a-node-app
Related tutorials
- How to Run an App and PostgreSQL Together with Docker ComposeYou will describe a Node.js app and a PostgreSQL 18 database in one compose.yaml, start both with one command, keep the data in a named volume, and keep the database password out of the file.
- Keep Snip healthy with probes and graceful shutdownYou will give the Snip Deployment startup, readiness and liveness probes with timings you can explain, a preStop pause and a grace period that let in-flight requests finish during a rollout, and watch readiness take a pod out of service when PostgreSQL stops while liveness leaves it running.
- How to Write a Dockerfile for a Node.js AppYou will write a Dockerfile for a small Express app on Node.js 26, build it into an image, run it as a container on port 3000 as a non-root user, and order the file so rebuilds take seconds.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials