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
dockerfiledockerfile
1234567891011121314151617# Stage 1: BuildFROM node:20-alpine AS builderWORKDIR /appCOPY package*.json ./RUN npm ciCOPY . .RUN npm run build# Stage 2: Minimal Production Runner (Under 90MB)FROM node:20-alpine AS runnerWORKDIR /appENV NODE_ENV=productionCOPY --from=builder /app/.next ./.nextCOPY --from=builder /app/package*.json ./RUN npm ci --only=productionUSER nodeCMD ["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 CodeIndustry 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.