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 Code, Cloud & Context
Subscribe to get the latest posts sent to your email.