Multi-Stage Image Builds

Multi-stage builds allow you to use multiple FROM statements in a single Dockerfile, separating the heavy build environment from the minimal runtime image.

1. Why Multi-Stage Builds Matter

Building modern React, Next.js, Go, or Java apps requires heavy SDK compilers, TypeScript tools, and devDependencies. By using multi-stage builds, you compile your code in a temporary build stage and copy only the compiled assets into a razor-thin production image!

2. Production Next.js / React Multi-Stage Dockerfile

# ==========================================
# STAGE 1: Build & Compile Stage
# ==========================================
FROM node:18-alpine AS builder
WORKDIR /app

# Copy dependency locks
COPY package*.json ./
RUN npm ci

# Copy source code and build production bundle
COPY . .
RUN npm run build

# ==========================================
# STAGE 2: Minimal Production Runtime Stage
# ==========================================
FROM node:18-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production

# Copy only production dependencies & compiled output from STAGE 1!
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
RUN npm ci --only=production

EXPOSE 3000
CMD ["npm", "start"]
Result: Image size shrinks from 1.2 GB (with node_modules & dev compilers) down to ~85 MB!

Next Up

Learn Container Security Practices: non-root users (USER node), vulnerability scanning, and read-only filesystems.

Next Lesson: Container Security Practices →