Sub topic 8
Your first multi-stage build
This chapter assumes you can write a basic Dockerfile and run containers with docker run. It also assumes you know that each instruction creates a layer and that the build cache reuses unchanged layers. Here you will turn a single-stage Dockerfile into a multi-stage one, see what the final image keeps and drops, and learn the errors people hit most often.
The problem with one stage
A single-stage Dockerfile ships everything it used to build the app. The compiler, headers, package manager caches and source files stay in the image because layers are never really removed. They are only hidden by later layers.
This example is a small C program. It is used here only because the effect is easy to see. The same idea applies to any language with a build step.
Create hello.c:
#include <stdio.h>
int main(void) {
puts("Hello from a small image");
return 0;
}Create Dockerfile.single:
FROM gcc:13
WORKDIR /src
COPY hello.c .
RUN gcc -O2 -o /usr/local/bin/hello hello.c
CMD ["hello"]Build and check the size:
docker build -f Dockerfile.single -t hello:single .
docker image ls hello:singleThe image is over 1 GB, because it contains the whole GCC toolchain. The running program needs none of it. The binary is a few kilobytes.
Two FROM lines, two stages
A multi-stage build is a Dockerfile with more than one FROM instruction. Each FROM starts a new stage with its own base image and its own filesystem. By default, the image you get is the last stage.
Create Dockerfile:
FROM gcc:13 AS build
WORKDIR /src
COPY hello.c .
RUN gcc -O2 -static -o /out/hello hello.c
FROM alpine:3.20
COPY --from=build /out/hello /usr/local/bin/hello
CMD ["hello"]Here is what each part does:
FROM gcc:13 AS buildstarts the first stage and gives it the namebuild.RUN gcc ... -o /out/hellowrites the compiled program to/out/helloinside thebuildstage.FROM alpine:3.20starts a second stage from a small base. Nothing frombuildis visible here unless you copy it.COPY --from=build /out/hello /usr/local/bin/hellocopies one file from thebuildstage's filesystem into this stage.
Build it and compare:
docker build -t hello:multi .
docker image ls hello
docker run --rm hello:multiThe multi-stage image is a few megabytes, almost all of it the Alpine base. The program prints Hello from a small image.
What the final image contains
The final image contains the layers of the last stage and nothing else. The layers of gcc:13 and the compile step are not part of hello:multi. You can confirm this with docker history:
docker history hello:multiYou should see only the Alpine layers, the COPY layer for the binary, and the CMD metadata. No gcc layers appear.
The earlier stages are not deleted from your machine, though. BuildKit keeps their layers in the build cache, so a rebuild with unchanged inputs skips the compile. docker image ls does not list the build stage because it was never tagged as an image. You can see cache usage with docker buildx du, and docker builder prune removes it.
How COPY --from finds its source
COPY --from=<source> accepts three kinds of source:
| Source | Example | Meaning |
|---|---|---|
| Stage name | `--from=build` | The stage declared with `AS build` |
| Stage index | `--from=0` | The first `FROM` in the file, counting from 0 |
| Image reference | `--from=nginx:1.27` | A separate image, pulled if needed |
Prefer names over indexes. Inserting a new stage at the top shifts every index and silently changes what --from=1 points to.
The image form is useful for borrowing a single file from a published image without making it your base:
FROM alpine:3.20
COPY --from=nginx:1.27 /etc/nginx/nginx.conf /tmp/nginx.confPaths in COPY --from are resolved inside the source stage's filesystem, not in your build context. This is the first thing to check when a copy fails.
Stages do not share state
A new FROM resets almost everything. These do not carry over from one stage to the next:
- The filesystem. Only what you copy explicitly is available.
WORKDIR,USER,ENVandCMD. Set them again in the stage that needs them.ARGvalues declared inside a stage. AnARGdeclared before the firstFROMcan be used inFROMlines, but to use it inside a stage you must redeclare it there withARG NAME.
The example above relies on this reset. The final stage does not inherit the gcc image's PATH or any other configuration.
Why -static matters here
The build stage is Debian-based and the final stage is Alpine. Debian uses glibc and Alpine uses musl, which are different C libraries. A normal dynamically linked binary built on Debian expects glibc at runtime. On Alpine it fails with an error that looks unrelated:
exec /usr/local/bin/hello: no such file or directoryThe file exists. The message refers to the missing dynamic loader that the binary asks for. Linking with -static puts the C library inside the binary, so the final image needs no matching libraries.
You have three ways to avoid this class of problem:
- Link statically, as above.
- Use a final base with the same C library as the build stage, for example
debian:bookworm-slimfor agcc:13build. - Copy the needed shared libraries into the final stage. This is fragile, and you would use it only when the other two are not possible.
You can check a binary before you copy it. In the build stage, ldd /out/hello prints not a dynamic executable for a static binary. For a dynamic one, it lists every library you would need at runtime.
Order matters for the cache
Stages use the same cache rules as single-stage builds. Each instruction's layer is reused if the instruction and its inputs are unchanged. A change invalidates that layer and everything after it within the same stage.
Two consequences follow:
- Editing
hello.crebuilds the compile step but not theFROM alpine:3.20stage's base layers. - The final stage's
COPY --from=builddepends on the content of the copied file. If the compile output is byte-identical after a rebuild, the finalCOPYlayer can still be reused.
BuildKit also builds stages in parallel when they do not depend on each other, and it skips stages that the final image does not need. A stage that nothing copies from is never built, unless you target it directly. The next chapter covers targeting.
Common mistakes
- Wrong path in
COPY --from. The error readsfailed to compute cache key: ... not found. Add a temporaryRUN ls -R /outto the build stage to see where the output really is. - Copying too much.
COPY --from=build /src /appbrings the whole source tree and any intermediate files into the final image. Copy only the built artifact. - Forgetting runtime files. A static binary may still need CA certificates, timezone data or a config file. Copy them in explicitly, or choose a base image that has them.
- Silent cache assumptions.
RUN apt-get updatein an old cached layer can leave you with stale package lists. Combineupdateandinstallin oneRUN. - Relying on stage order. Declare stages in dependency order. The final stage must be last, or you must select it with
--target.
Putting it together
The pattern you will reuse in every later chapter has three parts:
- A build stage with all compilers, SDKs and dev dependencies.
- A final stage from a small base, with only the runtime pieces.
- One or more
COPY --from=lines that move the finished artifacts across.
Everything else in this tutorial refines how you choose the final base, what you copy, and how you keep the build fast.
Exercise
You build a program in a golang:1.22 stage and copy the binary into alpine:3.20. The container exits with exec /app: no such file or directory, although docker run --rm img ls -l /app shows the file exists. What is the likely cause, and name two ways to fix it?
Show answer
The binary is dynamically linked against glibc, and Alpine uses musl, so the dynamic loader the binary asks for is missing. Fixes: build a static binary (for Go, set CGO_ENABLED=0), or use a final base image that has the same C library as the build stage, such as debian:bookworm-slim.
Exercise
A Dockerfile has FROM node:20 AS build followed by ENV NODE_ENV=production, then FROM node:20-slim and COPY --from=build /app/dist ./dist. Will NODE_ENV be set when the final container runs? Why?
Show answer
No. ENV is scoped to the stage where it is declared, and the new FROM starts from a fresh base. To set it in the final image, add ENV NODE_ENV=production after the final FROM.