Understanding of Docker multi-stage build:

  • Building an image requires a base image, and subsequent operations will be built based on the base image

  • There is a layered concept in the docker image file. Each time the RUN instruction is executed, the image will have one more layer, so the image size can be reduced by reducing the layers

  • When there are multiple froms, only the image of the last from is the root image of the image

Multi-stage build example in my own project deployment, here the binary compiled based on the golang base image is directly copied to the minimum image built based on alpine:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
FROM golang:1.12.7 as build
MAINTAINER wanzi <iwz2099@163.com>

# Compilation configuration related
ARG NAME=gaia
ARG FLAGS=-tags=jsoniter
ARG GOOS=linux
ARG GOARCH=amd64
ARG PORT_TO_EXPOSE=10020

ENV GOPROXY https://mirrors.aliyun.com/goproxy/
ENV GO111MODULE on WORKDIR /opt/gaia COPY . . RUN GOOS=$GOOS GOARCH=$GOARCH go build -mod vendor -ldflags="-s -w" -o $NAME $FLAGS FROM alpine WORKDIR /opt/gaia COPY --from=build /opt/gaia/gaia . RUN mkdir -p /opt/gaia/conf VOLUME ["/opt/gaia /conf"] CMD ["./gaia"] EXPOSE $PORT_TO_EXPOSE ```