SkillSprout
Chapter 1 · Lesson 10
Advanced
2 min read

Run as a Non-root User and Handle Health

Overview

A production Dockerfile should define not only files and commands, but also process ownership and health behavior. The default process should run as an unprivileged user, handle stop signals, and expose a meaningful health check.

Detailed Notes

Change to a non-root user

dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
USER node
CMD ["node", "server.js"]

COPY --chown=node:node assigns copied files to the node user. USER node changes the default account for following instructions and for the container process.

This does not remove every risk, but it prevents an application bug from automatically having host-root privileges inside the container namespace.

Add a health check

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3   CMD wget -q --spider http://127.0.0.1:3000/health || exit 1

Docker runs the command repeatedly inside the container:

  • interval: wait 30 seconds between checks;
  • timeout: allow 3 seconds for one check;
  • start-period: ignore failures while the application starts;
  • retries: require 3 failures before marking unhealthy.

A health endpoint should test application readiness, not just process existence. It might check database reachability or required dependencies.

Graceful shutdown

docker stop sends SIGTERM to the container's main process. The application should stop accepting new work, finish in-flight work and exit. Docker waits a default grace period before sending SIGKILL.

With the JSON CMD form, Node.js can become PID 1 and receive signals:

dockerfile
CMD ["node", "server.js"]

An application launched through an unnecessary shell can receive signals differently. Test shutdown behavior:

bash
docker run -d --name api my-api:1.0
docker stop api
docker logs api

The logs should show a clean shutdown message rather than an abrupt process termination.

Common Interview Questions

Finished this lesson?

0 of 27 lessons done · 0% of the course