Docker Multi-Stage Builds: Shrink Your Production Images by 80%
Docker Multi-Stage Builds: Shrink Your Production Images by 80% A naive Dockerfile for a Next.js app produces a 1.2GB image. Multi-stage builds get that under 200MB. Here's how. The Problem with Si...

Source: DEV Community
Docker Multi-Stage Builds: Shrink Your Production Images by 80% A naive Dockerfile for a Next.js app produces a 1.2GB image. Multi-stage builds get that under 200MB. Here's how. The Problem with Single-Stage Builds # Bad — everything ends up in production FROM node:20 WORKDIR /app COPY package*.json ./ RUN npm install # includes devDependencies COPY . . RUN npm run build CMD ["npm", "start"] # Result: ~1.2GB image with dev tools, build tools, source files Multi-Stage Build # Stage 1: Install dependencies FROM node:20-alpine AS deps WORKDIR /app COPY package*.json ./ RUN npm ci --only=production # Stage 2: Build the app FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build # Stage 3: Production image (only what's needed) FROM node:20-alpine AS runner WORKDIR /app ENV NODE_ENV=production # Copy only production deps and build output COPY --from=deps /app/node_modules ./node_modules COPY --from=builder /app/.next ./.next COPY --from=builder