Here is an example of an insecure Dockerfile that runs as root, leaks build-time secrets, and uses a bloated base image with unpatched OS vulnerabilities:
🥺 Vulnerable Code
# Vulnerable: Running as root, embedding secrets in build layers, and bloated base image
FROM node:18
WORKDIR /app
# Insecure: Leaking private npm token and secrets directly into image layer history
ARG NPM_TOKEN=npm_live_secret_token_12345
ENV DATABASE_URL="postgres://admin:password123@prod-db.internal:5432/main"
COPY package*.json ./
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && \
npm install && \
rm -f .npmrc
COPY . .
# Insecure: Defaults to root user (UID 0), granting full container breakout surface
EXPOSE 3000
CMD ["node", "server.js"]This Dockerfile contains three critical security anti-patterns: (1) It omits the USER directive, causing the application process to run as root (UID 0), which maximizes the impact of any container escape vulnerability; (2) It burns secrets directly into the build layers using ARG and ENV, meaning any user with access to the image can retrieve the production database credentials and NPM token via docker history; (3) It uses a full Debian-based node:18 image that contains hundreds of unnecessary operating system binaries (curl, apt, bash) that facilitate lateral movement.
😎 Secure Code
Here is a hardened version of the same Dockerfile using multi-stage builds, a minimal distroless runtime image, secret mounting, and an unprivileged non-root user:
# Secure: Multi-stage build, secret mounting, distroless runtime, and non-root execution
# Stage 1: Build stage with buildkit secret mount
FROM node:20-alpine AS builder
WORKDIR /build
COPY package*.json ./
# Secure: Secret mounted at runtime without persisting into final image layer history
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN=$(cat /run/secrets/npm_token) && \
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && \
npm ci --only=production && \
rm -f .npmrc
COPY . .
# Stage 2: Minimal Distroless runtime image (no shell, no package manager)
FROM gcr.io/distroless/nodejs20-debian12:nonroot
WORKDIR /app
# Copy production artifacts from builder stage
COPY --from=builder /build/node_modules ./node_modules
COPY --from=builder /build/server.js ./server.js
COPY --from=builder /build/package.json ./package.json
# Secure: Enforces non-root user (UID 65532 built into distroless)
USER nonroot:nonroot
EXPOSE 3000
CMD ["server.js"]The hardened Dockerfile leverages multi-stage builds to separate build dependencies from the runtime image. By using BuildKit secret mounting (-mount=type=secret), the NPM token is never saved to the layer history. The final stage uses Google's Distroless runtime image, which eliminates shells, package managers, and standard OS utilities. Finally, USER nonroot enforces that the process executes under UID 65532, preventing attackers from modifying system binaries or escaping to the host.