What is the method of multi-stage building in Docker?

Docker multi-stage build is a technique where multiple build stages are defined in a Dockerfile, allowing for smaller images and improved build efficiency. Each stage in the multi-stage build has its own base image and instructions, enabling different operations to be carried out in different stages.

By utilizing multi-stage builds, the construction process can be divided into multiple stages, with the output of each stage serving as the input for the next stage. This helps prevent the inclusion of building tools and dependencies in the final image, thus reducing the size of the image.

Here is an example Dockerfile using a multi-stage build:

# 第一个阶段,用于构建应用
FROM golang:1.15 as builder
WORKDIR /app
COPY . .
RUN go build -o myapp

# 第二个阶段,用于构建最终镜像
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/myapp .
CMD ["./myapp"]

In the example above, the first stage builds the application using a golang base image and then copies the compiled binary file to an alpine base image in the second stage. The final image only includes the final application and necessary runtime dependencies, without any build tools or compilation dependencies.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds