How do Docker multi-stage builds reduce image size and security risk?
Quick Summary: Multi-stage Dockerfiles use an initial builder stage containing compilers, Node/Maven toolchains, and dev dependencies to produce compiled artifacts, then copy only those final binaries into a tiny, non-root runtime stage.
Direct Interview Answer
Shipping compilers, build tools, npm caches, and .git history in production bloats container pulls from 80 MB to 1 GB+ and introduces hundreds of unneeded CVE packages.
Using multiple FROM ... AS builder blocks discards the heavy build environment completely and emits a clean production image running as a non-root USER.
Detailed Technical Explanation
Combine multi-stage builds with dependency-manifest caching: copy package-lock.json or pom.xml and install dependencies before copying volatile source files so Docker reuses cached dependency layers across code commits.
Practical Walkthrough
Two-stage Node.js Dockerfile dropping devDependencies and running as non-root node user.
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --omit=dev && chown -R node:node /app
USER node
CMD ["node", "dist/server.js"]
Minimal production image with TypeScript compiler excluded and non-root execution.
Real-World Production Use Case
Cutting EKS container startup pulls by 80% and passing enterprise Trivy/SOC2 image vulnerability scans.
Common Interview Mistakes to Avoid
- Copying the entire repository before running npm ci / pip install, busting layer cache on every code edit.
- Leaving .env files or build secrets inside intermediate image layers instead of BuildKit --mount=type=secret.