Infrastructure
Docker Multi-stage Builds
→ 日本語版を読むMulti-stage builds
In short, this refers to builds that use multiple FROM statements. Each FROM clause starts a new build stage.
By using COPY to copy only the necessary build artifacts (i.e., files) from a previous stage into the new stage, you can reduce the final image size.
In the example below, the second FROM clause uses the scratch image (an empty image), and by copying only the /bin/hello file with COPY, an image containing only the /bin/hello binary is created.
FROM golang:1.21 AS build
WORKDIR /src
COPY <<EOF /src/main.go
package main
import "fmt"
func main() {
fmt.Println("hello, world")
}
EOF
RUN go build -o /bin/hello ./main.go
FROM scratch
COPY --from=build /bin/hello /bin/hello
CMD ["/bin/hello"]
In the first FROM clause, the stage is named build using AS. Then, in the second stage, COPY --from=build copies files from the stage named build.
You can also reference a previous stage in a FROM clause, as shown below.
# syntax=docker/dockerfile:1
FROM alpine:latest AS builder
RUN apk --no-cache add build-base
FROM builder AS build1
COPY source1.cpp source.cpp
RUN g++ -o /binary source.cpp
FROM builder AS build2
COPY source2.cpp source.cpp
RUN g++ -o /binary source.cpp