QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Intermediate 18 min readModule: Module 4: Multi-Stage Dockerfiles & Optimization

Multi-Stage Builds & Container Image Hardening

Shrink Docker image sizes by 90% and eliminate vulnerabilities using multi-stage builds and non-root users.

What You Will Learn in This Lesson

  • Multi-stage Docker builds: separating build environment from minimal runtime
  • Docker layer caching order optimization
  • Running containers as unprivileged non-root users (USER node)

Introduction & Core Concept

Multi-stage builds allow you to use multiple FROM statements in your Dockerfile. You can selectively copy artifacts from one stage to another, leaving behind everything you don't need in the final image.
WHY DOES THIS MATTER IN THE REAL WORLD?

Multi-stage builds prevent compilers, build tools, and source code from bloating production images and creating security attack vectors.

Production Next.js Multi-Stage Dockerfile

dockerfile
dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Minimal Production Runner (Under 90MB)
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
USER node
CMD ["npm", "start"]

Line-by-Line Technical Breakdown

1Copying package.json before source files leverages Docker layer caching to prevent re-installing dependencies on code changes.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[DOCKERFILE]
DOCKERFILE SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Always include a .dockerignore file containing node_modules, .git, and .env.

Lesson Summary & Core Takeaways

  • Multi-stage builds produce tiny, secure, and fast-starting container images.