Container Security: Hardening Docker Images for Production
A default Docker image is full of attack surface — package managers, shells, unnecessary libraries. Production containers should contain exactly what they need and nothing else.
Multi-Stage Builds
# Build stage
FROM node:22-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build
# Production stage
FROM gcr.io/distroless/nodejs22-debian12
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
USER nonroot
CMD ["dist/server.js"]
Distroless Images
Google's distroless images contain no shell, no package manager, no unnecessary binaries. An attacker who gets RCE cannot apt install tools, cannot spawn a reverse shell, and cannot explore the filesystem easily.
Runtime Security Checklist
–
Run as non-root user (USER nonroot)
–
Read-only filesystem (readOnlyRootFilesystem: true)
–
Drop all capabilities (drop: [ALL])
–
No privilege escalation (allowPrivilegeEscalation: false)
–
Resource limits (prevent crypto-mining)
–
Network policies (restrict egress)