Security and production best practices
Running containers in production means thinking about security, reliability and observability. This lesson is a checklist that experienced teams follow.
1. Don't run as root
By default, processes in a container run as root. If an attacker breaks your app, they're root inside the container, one step closer to the host.
FROM node:22-alpine
WORKDIR /app
COPY --chown=node:node . .
RUN npm ci --omit=dev
USER node # the official node image ships a 'node' user
CMD ["node", "server.js"]For other images, create a user:
RUN addgroup -S app && adduser -S app -G app
USER app2. Never bake secrets into images
Anything in an image (including ENV, ARG and files deleted in later layers) can be extracted by anyone who pulls it.
# ✗ NEVER
ENV DB_PASSWORD=hunter2
COPY .env .✓ Pass secrets at run time (environment variables from your platform's secret store, Docker/Kubernetes secrets, or mounted files). For secrets needed at build time (like a private npm token), use BuildKit secret mounts:
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm cidocker build --secret id=npmrc,src=$HOME/.npmrc .3. Pin and scan images
FROM node:22.11-alpine3.20 # pin versions…
# FROM node@sha256:abc123... # …or pin by digest for full reproducibilityScan for known vulnerabilities (CVEs) in CI:
docker scout cves my-app:1.0
trivy image my-app:1.0Rebuild regularly so you pick up base image security patches.
4. Health checks
Tell Docker how to check that your app is actually working, not just running:
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD wget -qO- http://localhost:3000/health || exit 1Orchestrators use health checks to restart broken containers and to route traffic only to healthy ones.
5. Handle shutdown signals properly
When stopping, Docker sends SIGTERM, waits 10 s, then sends SIGKILL. Your app should finish in-flight requests and close connections on SIGTERM:
process.on('SIGTERM', () => {
server.close(() => {
db.end();
process.exit(0);
});
});- Use the exec form
CMD ["node", "server.js"], notCMD node server.js. The shell form wraps your app in/bin/sh, which doesn't forward signals. - Add
--init(ortini) so zombie processes are reaped.
6. Limit resources
A runaway container shouldn't take down the whole host:
docker run -d --memory=512m --cpus=1.0 --pids-limit=200 my-app# compose.yaml
services:
api:
deploy:
resources:
limits: { cpus: "1.0", memory: 512M }7. Lock down the runtime
# --read-only + --tmpfs: immutable filesystem, writable /tmp only
# --cap-drop=ALL: drop all Linux capabilities
# no-new-privileges: block privilege escalation
docker run -d \
--read-only --tmpfs /tmp \
--cap-drop=ALL \
--security-opt=no-new-privileges \
my-app- Never run
--privilegedin production. - Never mount
/var/run/docker.sockinto an app container. It gives full control of the host.
8. Logs go to stdout
Don't write log files inside containers. Write to stdout/stderr, and Docker or your platform collects them (docker logs, CloudWatch, Loki, ELK). Use structured JSON logs in production.
9. Restart policies
docker run -d --restart unless-stopped my-app| Policy | Behaviour |
|---|---|
no |
Never restart (default) |
on-failure[:N] |
Restart on non-zero exit |
unless-stopped |
Always, unless you stopped it manually |
always |
Always, even after a manual stop + daemon restart |
The production checklist
- Multi-stage build, small base,
.dockerignore - Pinned base image versions; scanned in CI
- Runs as non-root
USER - No secrets in the image
-
HEALTHCHECKand gracefulSIGTERMhandling - Memory/CPU limits and a restart policy
- Logs to stdout, config via environment variables (the 12-factor app principles)
Practice
Take your multi-stage image from the previous lesson and apply every item on the checklist. Then run docker scout cves or trivy and fix anything high-severity by updating the base image.
1.Why is ENV API_KEY=... in a Dockerfile dangerous?
2.Why prefer CMD ["node","server.js"] over CMD node server.js?