Sobes.tech
Junior — Middle

How can a multi-stage container image build be implemented?

sobes.tech AI

Answer from AI

Multi-stage build in Docker allows creating multiple build stages within a single Dockerfile, which helps reduce the size of the final image and separate the compilation stage from the runtime stage.

The main idea is to use multiple FROM instructions in one Dockerfile, where each subsequent stage can use artifacts from the previous ones.

Example:

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

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

Here, the application is first built in Go, and then only the compiled binary is copied into the final image, without source files and build tools.