Sobes.tech
Middle

How do you use multistage build to optimize Docker images?

sobes.tech AI

Answer from AI

Multistage build allows the use of multiple stages in a Dockerfile, where each stage performs its own task. The result of one stage (for example, the built artifact) is passed to the next stage, but intermediate layers from previous stages are not included in the final image.

Example of usage for building a Go application:

# Build stage
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o /app/myapp

# Final stage
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp /app/
CMD ["/app/myapp"]

Advantages:

  • Reducing image size: The final image contains only the built application and necessary dependencies, not build tools, source code, or intermediate files.
  • Separation of concerns: The compilation/build logic is separated from deployment logic.
  • Enhanced security: Reduces the attack surface by excluding unnecessary tools and libraries from the final image.
  • Faster builds: Layer caching between stages can speed up repeated builds.

For example, in the provided Dockerfile, the first layer builder is used for compiling the Go application. The second layer, starting with FROM alpine:latest, copies only the compiled application from the first layer (COPY --from=builder /app/myapp /app/) into a clean base image. As a result, the final image contains only the executable file and the basic operating system, without the Go compiler and source code.

This significantly reduces the image size compared to the traditional approach where build and runtime occur in the same container.