Quay lại TIL
2023-05-28Devopsintermediate5 min

Docker Multi-Stage Builds


# Docker Multi-Stage Builds

Today I learned how to optimize Docker images using multi-stage builds, a technique that significantly reduces image size while maintaining a clean Dockerfile.

## The Problem

Traditional Docker builds often result in bloated images that include build tools, dependencies, and artifacts that aren't needed at runtime. This increases deployment time, storage costs, and security risks.

## Multi-Stage Builds Solution

Multi-stage builds allow you to use multiple FROM statements in your Dockerfile. Each FROM statement begins a new stage that can selectively copy artifacts from previous stages.

## Benefits I Observed

- Reduced our Node.js application image from 1.2GB to just 150MB
- Simplified our CI/CD pipeline by eliminating separate build and packaging steps
- Improved security by excluding build tools and unnecessary dependencies from the final image
- Faster deployments due to smaller image size

This approach has now become our standard practice for all containerized applications.

Code Example

# Build stage
FROM node:16 AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Production stage
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]