Intern
What is Multistage build in Docker and why is it needed?
sobes.tech AI
Answer from AI
Multistage build in Docker is a method of creating Docker images that uses multiple build stages within a single Dockerfile. In the initial stages, the application is compiled and prepared, and in the final stages, a minimal final image is formed without unnecessary tools and source code.
Why is it needed:
- Reduces the size of the final image, as only the files necessary for running are included.
- Increases security — build tools and source code are not included in the image.
- Simplifies the build process, as all stages are described in one Dockerfile.
Example:
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp
FROM alpine:latest
COPY --from=builder /app/myapp /usr/local/bin/myapp
CMD ["myapp"]
Here, the application is first built in Go, and then only the compiled binary is copied into the final image.