Multi-stage builds
Build in one image, run in another.
Building needs a compiler, a package manager and the sources, while running needs only the finished program. If you build and run in the same image, everything extra goes to the server: the image weighs hundreds of megabytes and contains tools nobody on the server needs. A multi-stage build solves this: one Dockerfile has several FROM lines, and only what is needed is copied into the final image.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server
FROM alpine:3.20
COPY --from=build /out/server /usr/local/bin/server
CMD ["server"]
The first stage is named build and contains the whole Go toolchain. The second starts from a small base image, and COPY --from=build moves a single finished file into it.
The final image is only the last stage. The compiler, the sources and the module cache stay in the intermediate stage and never reach the server. For Go the result often weighs tens of megabytes instead of hundreds. The same trick works for a frontend: build on a Node.js image and copy the resulting static files into a web server image.
Stages can be built separately with the --target flag. For example, docker build --target build . stops at the build stage, which is a handy place to run tests. The layer cache works at every stage, so the rules about instruction order apply here too: dependencies are copied before the code.
A common mistake is to copy a binary that depends on system libraries into an image that does not have them. The program fails to start with a message like “not found”, even though the file is there. For Go this is fixed with CGO_ENABLED=0; for other languages, with a base image of the same system as the build stage.
Practice
What reaches the server
A Dockerfile has two stages:
buildwith a compiler and a final one onalpine. What ends up in the final image?- Both stages in full
- Only the last stage and explicitly copied files
- Only the build stage
- The sources and the module cache
Properties of a multi-stage build
Which statements are true? Mark all.
- COPY --from=build copies files from the build stage
- --target lets you build the image up to a given stage
- The layer cache is turned off in a multi-stage build
- The final image is usually smaller than with a single-stage build
Copying between stages
Which flag of the
COPYinstruction takes files from another build stage? Write the flag without a value.