Tips and Tricks #46: Use Multi-Stage Docker Builds for Smaller Images

Reduce container image size by separating build and runtime stages.

Code Snippet

# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Runtime stage - only production dependencies
FROM node:20-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production

# Copy only what's needed
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production

USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]

Why This Helps

  • Image size reduced by 60-80%
  • Faster deployments and pulls
  • Smaller attack surface in production

How to Test

  • Compare image sizes: docker images
  • Verify app runs correctly from final stage

When to Use

Any containerized application. Essential for production deployments.

Performance/Security Notes

Use alpine base images when possible. Don’t include dev dependencies or source code in final image.

References


Try this tip in your next project and share your results in the comments!


Discover more from Byte Architect

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.