Sub topic 13
Documenting ports and checking health
This chapter covers two instructions that describe how a running container behaves: EXPOSE and HEALTHCHECK. It assumes you can write a basic Dockerfile, build an image, and run it with docker run. It also assumes you know what -p does on the command line.
What EXPOSE does
EXPOSE records which port the application inside the container listens on. It is metadata stored in the image configuration.
EXPOSE 3000
EXPOSE 8080/tcp
EXPOSE 5353/udpThe protocol defaults to TCP. You can list several ports, and you can give each port its own EXPOSE line.
EXPOSE does not publish the port. It does not open anything on the host, and it does not change what the application listens on. If the app binds to port 4000 and the Dockerfile says EXPOSE 3000, the container still listens on 4000.
To reach the container from the host, you publish a port when you run it:
docker run --rm -p 3000:3000 myapp:1.0The -p flag maps host_port:container_port. It works whether or not the image has an EXPOSE line. You can publish a port that was never exposed, and exposing a port without publishing it leaves it unreachable from the host.
What EXPOSE is still good for
EXPOSE has three practical uses.
- Documentation. Anyone reading the Dockerfile or running
docker inspectcan see which port the app expects. - Publishing all exposed ports. The
-Pflag (capital P) publishes every exposed port to a random high port on the host. - Tooling. Some orchestration and reverse-proxy tools read the exposed ports from image metadata to pick a default.
docker run -d --rm -P --name web myapp:1.0
docker port webdocker port web prints the mapping that Docker chose, for example 3000/tcp -> 0.0.0.0:32768.
You can read the recorded metadata directly:
docker inspect --format '{{json .Config.ExposedPorts}}' myapp:1.0Container-to-container traffic
Containers on the same user-defined network can reach each other on any port the application listens on. They do not need EXPOSE or -p. Publishing is only needed for traffic that comes from outside Docker, such as your browser on the host.
Why a running container is not always a healthy one
Docker considers a container "running" as long as its main process is alive. That says nothing about whether the application works. A web server can hang, lose its database connection, or run out of worker threads while the process stays up. Without a health check, Docker reports the container as Up the whole time.
HEALTHCHECK tells Docker how to test the application. Docker runs a command inside the container on a schedule and tracks the result.
HEALTHCHECK syntax
HEALTHCHECK [OPTIONS] CMD commandThe command's exit code decides the result:
| Exit code | Meaning |
|---|---|
| 0 | Healthy |
| 1 | Unhealthy |
| 2 | Reserved. Do not use it. |
Any non-zero code other than 2 is also treated as a failure in practice, but stick to 0 and 1 so the intent is clear.
The options control timing:
| Option | Default | Meaning |
|---|---|---|
| `--interval` | 30s | Time between checks |
| `--timeout` | 30s | A check that runs longer than this counts as a failure |
| `--start-period` | 0s | Grace time for startup. Failures in this window do not count toward the retry limit. |
| `--start-interval` | 5s | Time between checks during the start period (needs a recent Docker Engine) |
| `--retries` | 3 | Consecutive failures needed to mark the container unhealthy |
A working example
The Node.js image from earlier chapters has a node:20-slim base. That image does not include curl, but it does include Node, so you can write the probe in JavaScript. Here is a small server with a /health route, followed by the Dockerfile that checks it.
// server.js
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/health") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("ok");
return;
}
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("hello\n");
});
server.listen(3000, "0.0.0.0", () => {
console.log("listening on 3000");
});FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \
CMD node -e "require('http').get('http://127.0.0.1:3000/health', r => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"
USER node
CMD ["node", "server.js"]The probe makes an HTTP request to the local /health route. It exits 0 on a 200 response and 1 on any other status or on a connection error. Because the probe runs inside the container, it uses 127.0.0.1 and does not depend on any published port.
Build and run it, then watch the status change:
docker build -t myapp:1.0 .
docker run -d --rm --name web -p 3000:3000 myapp:1.0
docker ps --format 'table {{.Names}}\t{{.Status}}'Right after start, the status reads Up 2 seconds (health: starting). After the first successful check it reads (healthy).
To see the recent probe results, including output and exit codes:
docker inspect --format '{{json .State.Health}}' webThe health state machine
A container with a health check moves through three states.
A single failure does not change the state. The container becomes unhealthy only after --retries consecutive failures. One success resets the failure count.
Choosing a good check
A health check runs every few seconds for the life of the container, so its design matters.
- Test the app, not just the process. A check that only looks for a listening socket will pass while the request handler is deadlocked. An HTTP request to a lightweight route is better.
- Keep it cheap. The check should not run heavy queries or call slow third-party services. A slow check can itself cause load or timeouts.
- Think about dependencies. If
/healthchecks the database and the database is down, every replica of your app turns unhealthy at once. Some teams separate a shallow check (is this process serving?) from a deeper readiness check. Choose deliberately. - Set
--start-periodfor slow starters. Apps that load large data or warm caches need time. Without a grace period, early failures can mark the container unhealthy before it had a chance. - Use a tool that exists in the image. Slim and distroless images often lack
curlandwget. Either install one, use the language runtime as shown above, or compile a tiny probe binary into the image.
Exec form and shell form
HEALTHCHECK CMD accepts both forms, as CMD does. The shell form runs through /bin/sh -c, so it needs a shell in the image. The exec form runs the program directly:
HEALTHCHECK --interval=30s --timeout=3s \
CMD ["wget", "-q", "--spider", "http://127.0.0.1:8080/health"]This example assumes wget exists in the image, as it does on Alpine-based images through BusyBox.
Disabling an inherited check
A child image inherits the health check of its base image. To turn it off, write:
HEALTHCHECK NONEOnly one HEALTHCHECK instruction takes effect in a Dockerfile. If you write several, the last one wins.
What Docker does with the result
By default, the health status is informational. Docker does not restart an unhealthy container. Standalone docker run only reports the state. What reacts to it depends on the platform:
- Docker Compose can make one service wait for another with
depends_onandcondition: service_healthy. - Docker Swarm replaces unhealthy service tasks.
- Kubernetes ignores the Dockerfile
HEALTHCHECKand uses its own liveness, readiness, and startup probes defined in the pod spec. - Plain Docker needs a restart policy and a watcher script if you want automatic recovery. A restart policy such as
--restart=on-failurereacts to process exit, not to an unhealthy state.
Because of this, treat HEALTHCHECK as a signal that other tools consume. Confirm that your deployment target reads it before you rely on it.
Common mistakes
- Checking from the host's point of view. The probe runs inside the container. Use
127.0.0.1and the container's port, not the published host port. - Missing tool in the image. The check fails every time with "executable file not found", and the container turns unhealthy. Test the probe with
docker exec web <command>first. - Timeout longer than interval. Checks then overlap in practice and generate noise. Keep the timeout well below the interval.
- No start period. A slow application is marked unhealthy during normal startup.
- Assuming EXPOSE publishes. It does not. Use
-p.
Exercise
A teammate's image has EXPOSE 8080 and a HEALTHCHECK that runs curl -f http://localhost:8080/health. They start it with docker run -d myapp and then run curl localhost:8080 on the host, which is refused. docker ps shows the container as (unhealthy) with the message "curl: not found" in docker inspect. List the two separate problems and the fix for each.
Show answer
First, the port is not published. EXPOSE only documents the port, so the run command needs -p 8080:8080. Second, the image does not contain curl, so every health check fails and the container turns unhealthy. Fix this by installing curl in the image, switching to a probe that the image already supports such as wget or the language runtime, or building a small probe into the application binary. Fixing only one of these leaves the other symptom in place. The unhealthy status comes from the missing tool, and the refused connection comes from the missing -p.
Exercise
You set --interval=10s --timeout=2s --retries=3 --start-period=30s. The app needs 20 seconds to start, and the first checks during startup fail. Is the container marked unhealthy during that time? What happens if the app is still failing after 60 seconds?
Show answer
It is not marked unhealthy during the first 30 seconds, because failures inside the start period do not count toward the retry limit. A successful check inside the start period moves the container to healthy immediately. If the app is still failing after the start period ends, three consecutive failures, about 30 seconds at a 10 second interval, move the container to unhealthy.