This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: docker-security-hardening

Docker Multi-Stage & Non-Root Hardening Standard

Production Dockerfile hardening: multi-stage builds, non-root user execution, minimal base images (distroless/alpine), and HEALTHCHECK directives.

Prohibited Anti-Pattern: AI runs containers as root (USER 0), bundles devDependencies into final production images, or omits HEALTHCHECK.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Docker Multi-Stage & Non-Root Hardening Standard - Production Dockerfile hardening: multi-stage builds, non-root user execution, minimal base images (distroless/alpine), and HEALTHCHECK directives.
globs: Dockerfile*, docker-compose*.yml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/docker-security-hardening"
---

# Docker Multi-Stage & Non-Root Hardening Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: AI runs containers as root (USER 0), bundles devDependencies into final production images, or omits HEALTHCHECK.

## System Constraints
You are a container security specialist. Docker containers must never run as root. Always create and switch to an unprivileged user (USER appuser). Use multi-stage builds to discard build tools, compilers, and source artifacts from the final image. Include explicit HEALTHCHECK instructions.

## Strict Guidelines
- 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.
- Use specific immutable image digest tags (node:22-alpine3.20) rather than `:latest`.
- Define HEALTHCHECK to allow orchestrators to detect deadlocked processes.

## Bad vs Good Implementations
### Hardened Non-Root Multi-Stage Dockerfile

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Runs as root with 1GB+ attack surface including npm, compilers, and all devDependencies.
```dockerfile
# CRITICAL FLAW: Single stage running as root with dev tools
FROM node:latest
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "server.js"]
```

#### Production Standard (Correct)
> **Standard**: Reduces attack surface to minimum, drops root privileges, and checks health automatically.
```dockerfile
# Production Standard: Multi-stage with unprivileged non-root user
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --production

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
USER appuser
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1
EXPOSE 3000
CMD ["node", "dist/server.js"]
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

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.

Framework Paradigm Shift & Drift MechanicsLLMs default to quick-start Dockerfiles that run as `root` by default, use bloated `ubuntu:latest` or `node:latest` images containing package managers and compilers, and embed secrets or build tokens directly into intermediate image layers.
Failure Modes & Production Blast Radius

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 ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
Root User Privilege EscalationDockerfile omits `USER` instruction, running the application process as UID 0Critical
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 LayersAI copies `.env` or uses `ARG SECRET_KEY` directly in Dockerfile `RUN` stepsCritical
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.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

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

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Separate build dependencies from runtime using multi-stage builds.

Separate build dependencies from runtime using multi-stage builds.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Use specific immutable image digest tags (node

Use specific immutable image digest tags (node:22-alpine3.20) rather than `:latest`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Define HEALTHCHECK to allow orchestrators to detect deadlocked processes.

Define HEALTHCHECK to allow orchestrators to detect deadlocked processes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

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

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Docker