Optimize your Docker images for production using multi-stage builds to reduce image size and improve security.
Multi-stage builds allow you to create optimized Docker images by using multiple FROM statements in your Dockerfile. This technique dramatically reduces image size and improves security.
Basic Multi-Stage Build
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
EXPOSE 3000
CMD ["node", "dist/index.js"] Benefits of Multi-Stage Builds
Smaller final images by excluding build tools and dependencies. Better security by minimizing attack surface. Faster deployment due to smaller image size. Clear separation between build and runtime environments.
Advanced Example with Testing
# Dependencies stage
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Test stage (can be run separately)
FROM builder AS test
RUN npm run test
# Production stage
FROM node:18-alpine AS production
ENV NODE_ENV=production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"] Multi-stage builds are essential for production Docker images. They keep your images lean, secure, and fast to deploy while maintaining a clean build process.
Found this helpful?
I write about software engineering, architecture, and best practices. Check out more articles or get in touch.