Review container health-check configuration

Check service health as well as whether its process is running.

Description

A running process can still fail to serve requests. Docker’s HEALTHCHECK reports the result of a command run inside the container.

Potential impact

A check with too short a timeout can mark a working service as unhealthy. Docker does not restart a container solely because it is unhealthy.

Remediation

Check a real service endpoint with a command available in the image. Set the startup grace period, timeout, and failure threshold for your app. On Kubernetes, configure startup, readiness, and liveness probes as needed. Test how the deployment routes traffic and recovers after a failure.

Examples

Include package.json, a lockfile, and server.js in the build context. Every 30 seconds, the example uses Node’s HTTP module to check /health. The check requires HTTP 200 and fails on a connection error or a five-second timeout.

Before

dockerfile
FROM node:22-alpine

WORKDIR /app
COPY . .
RUN npm ci
EXPOSE 3000
CMD ["node", "server.js"]

After

dockerfile
FROM node:22-alpine

WORKDIR /app
COPY . .
RUN npm ci
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s 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))"
CMD ["node", "server.js"]

References