Docker 2 Multistage Build

  • reduce img size
  • improve performance of container

A Docker multi-stage build is a method for creating optimized Docker images by using multiple FROM statements in a single Dockerfile

why to use multi stage builds :

  • Reduced Image Size: You avoid including unnecessary build tools and dependencies in the final image.
  • Improved Security: Only the minimal runtime environment is included, reducing the attack surface.
  • Simplified Maintenance: No need for separate Dockerfiles for building and running the application.

Example: Multi-Stage Build for a Go Application

# Stage 1: Build
FROM golang:1.20 AS build
WORKDIR /app
COPY . .
RUN go build -o main .

# Stage 2: Runtime
FROM alpine:latest
WORKDIR /app
COPY --from=build /app/main .
CMD ["./main"]
# Stage 1: Build
FROM node:18 AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

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

Best Practices

  • Use minimal base images for the runtime stage (e.g., alpine, debian-slim).
  • Keep the build and runtime stages separate to avoid unnecessary dependencies.
  • Always pin image versions to prevent unexpected changes