Understanding Docker Multi-stage Builds:

  • Building an image requires a base image; all subsequent operations are based on this base image.
  • Docker image files have a layered structure. Each RUN instruction adds a new layer, so reducing the number of layers helps minimize image size.
  • When multiple FROM instructions are used, only the last FROM image becomes the root image of the final build.

Example of multi-stage build in my own project deployment: Here, we compile a binary using the Golang base image and then directly copy it into a minimal Alpine-based image:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
FROM golang:1.12.7 as build
MAINTAINER wanzi <iwz2099@163.com>

# Compilation configuration
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