Skip to main content
Docker Intermediate Practical Coding Topic: Dockerfile Optimization

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.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

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.

Code Example — DOCKERFILE
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"]
Expected Output / Verification
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.
Topics: #docker #multi-stage #security #caching
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.