Your Docker image is 1.2GB when it should be 120MB? Multi-stage builds eliminate build dependencies from your final image.
The Problem – Single Stage Build:
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install # Installs 300MB of dev dependencies
COPY . .
RUN npm run build # Creates 10MB production build
CMD ["node", "dist/server.js"]
# Result: 1.2GB image (Node base + dependencies + source + build artifacts)
The Solution – Multi-Stage Build:
# Stage 1: Build
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Stage 2: Production
FROM node:18-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm install --production # Only production dependencies
CMD ["node", "dist/server.js"]
# Result: 180MB image (Slim base + production deps + compiled code)
Why This Works:
Multi-stage builds use multiple FROM statements. Each FROM starts a new build stage. COPY –from=STAGE lets you selectively copy artifacts from earlier stages. Everything from the ‘builder’ stage (source code, dev dependencies, intermediate files) is discarded in the final image.
Real Example – C# Application:
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["MyApp.csproj", "."]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish
# Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]
# Result: 220MB vs 1.8GB with SDK image
The Math:
.NET SDK image: 1.8GB (includes compilers, dev tools, debug symbols)
ASP.NET runtime image: 180MB (just the runtime)
Your app: 40MB (compiled DLLs)
Final image: 220MB = 87% size reduction
Pro Tip – Use Alpine for Even Smaller Images:
FROM node:18-alpine # 175MB instead of 1GB
FROM python:3.11-alpine # 50MB instead of 900MB
FROM nginx:alpine # 23MB instead of 135MB
Alpine Linux uses musl libc instead of glibc, cutting base OS size by 90%. Only downside: some packages have compatibility issues with musl.
