Architectural Invariant Design: Docker Multi-Stage & Non-Root Hardening Standard
Production Docker containerization requires defense-in-depth: non-root user execution, minimal base images (Chainguard, Distroless, or Alpine), multi-stage builds, and read-only root filesystems to mitigate privilege escalation and container breakout attacks.
Hazard Analysis: What Breaks Without This Rule
The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:
| Failure Mode | AI Symptom (The Anti-Pattern) | Severity | Production Impact & Remedy |
|---|---|---|---|
| Root User Privilege Escalation | Dockerfile omits `USER` instruction, running the application process as UID 0 | Critical | An application remote code execution (RCE) vulnerability allows full container takeover and host filesystem compromise. Create a dedicated non-privileged user and switch to it: `USER nonroot:nonroot` or `USER 10001:10001`. |
| Secret Leakage in Build Cache Layers | AI copies `.env` or uses `ARG SECRET_KEY` directly in Dockerfile `RUN` steps | Critical | Secrets remain permanently visible in `docker history` and exported image layers even if deleted later. Use BuildKit secret mounts: `RUN --mount=type=secret,id=mysecret ...` so credentials never enter the image metadata. |
Step-by-Step Production Directives
Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:
Never run as root. Add `RUN addgroup -S app && adduser -S app -G app` and `USER app`.
Never run as root. Add `RUN addgroup -S app && adduser -S app -G app` and `USER app`.
Separate build dependencies from runtime using multi-stage builds.
Separate build dependencies from runtime using multi-stage builds.
Use specific immutable image digest tags (node
Use specific immutable image digest tags (node:22-alpine3.20) rather than `:latest`.
Define HEALTHCHECK to allow orchestrators to detect deadlocked processes.
Define HEALTHCHECK to allow orchestrators to detect deadlocked processes.
Frequently Asked Technical Questions
Common questions developers face when configuring AI coding assistants for this stack:
Q:Why should Docker containers never run as root?
Running as root gives an attacker the same kernel capabilities as root on the host if a container escape vulnerability exists. Non-root execution strictly enforces user namespace boundaries.
Q:What is the recommended minimal base image for production Node.js and Go?
For Go, use `gcr.io/distroless/static` or `scratch` for a truly zero-CVE attack surface. For Node.js, use `gcr.io/distroless/nodejs20-debian12` or `cgr.dev/chainguard/node`.