
Docker Multi-Stage Builds: Cut Your Image Size by 80%
Docker Multi-Stage Builds: Cut Your Image Size by 80% A Node.js app with a standard Dockerfile can easily produce an 800MB+ image. The same app with a multi-stage build: 80-120MB. Here's how it works and how to implement it. Why Images Get So Big A typical Node.js Dockerfile: FROM node:20 WORKDIR /app COPY package*.json ./ RUN npm install # Installs devDependencies too COPY . . RUN npm run build CMD ["node", "dist/server.js"] Problems: node:20 base image is ~900MB npm install includes all devDependencies (TypeScript, webpack, etc.) Source files, test files, build tools all end up in the final image The Multi-Stage Solution # Stage 1: Build FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci # Install everything including devDeps COPY . . RUN npm run build # Compile TypeScript, etc. # Stage 2: Production FROM node:20-alpine AS production WORKDIR /app ENV NODE_ENV=production # Only copy what's needed for production COPY --from=builder /app/dist ./dist COPY --from
Continue reading on Dev.to DevOps
Opens in a new tab



