Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DK
Docker
0/10 completed
Beginner
Why containers?Install Docker and run your first containerImages vs containers
Intermediate
Writing a DockerfileVolumes and persistent dataNetworking and ports
Advanced
Docker ComposeMulti-stage builds and small images
Pro
Security and production best practicesRegistries and CI/CD
Tracks / Docker / Pro

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.

dockerfile
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:

dockerfile
RUN addgroup -S app && adduser -S app -G app
USER app

2. 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.

dockerfile
# ✗ 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:

dockerfile
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
bash
docker build --secret id=npmrc,src=$HOME/.npmrc .

3. Pin and scan images

dockerfile
FROM node:22.11-alpine3.20     # pin versions…
# FROM node@sha256:abc123...   # …or pin by digest for full reproducibility

Scan for known vulnerabilities (CVEs) in CI:

bash
docker scout cves my-app:1.0
trivy image my-app:1.0

Rebuild 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:

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget -qO- http://localhost:3000/health || exit 1

Orchestrators 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:

js
process.on('SIGTERM', () => {
  server.close(() => {
    db.end();
    process.exit(0);
  });
});
  • Use the exec form CMD ["node", "server.js"], not CMD node server.js. The shell form wraps your app in /bin/sh, which doesn't forward signals.
  • Add --init (or tini) so zombie processes are reaped.

6. Limit resources

A runaway container shouldn't take down the whole host:

bash
docker run -d --memory=512m --cpus=1.0 --pids-limit=200 my-app
yaml
# compose.yaml
services:
  api:
    deploy:
      resources:
        limits: { cpus: "1.0", memory: 512M }

7. Lock down the runtime

bash
# --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 --privileged in production.
  • Never mount /var/run/docker.sock into 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

bash
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
  • HEALTHCHECK and graceful SIGTERM handling
  • 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.

✎ Check your understanding

1.Why is ENV API_KEY=... in a Dockerfile dangerous?

2.Why prefer CMD ["node","server.js"] over CMD node server.js?

← Multi-stage builds and small images