Sub topic 9
Naming stages and building a single target
This chapter assumes you can read a multi-stage Dockerfile, know that COPY --from copies files between stages, and can run docker build and docker run. It covers how to name stages, how stages refer to each other, and how --target stops a build at a chosen stage.
Why stages need names
Every FROM instruction starts a new stage. Without names, Docker numbers stages from zero in the order they appear. You can copy from a stage by number:
FROM golang:1.22
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
FROM scratch
COPY --from=0 /out/app /app
ENTRYPOINT ["/app"]This works, but it breaks easily. If you insert a new stage at the top, such as a stage that downloads dependencies, 0 now points at the wrong stage. The error may not be obvious. You might copy from a stage that has no /out/app, or copy a file that exists but is stale.
Name the stage with AS instead:
FROM golang:1.22 AS buildThen refer to it with COPY --from=build. The name stays valid when you reorder or add stages.
Rules for stage names
- A name is set with
FROM <image> AS <name>. TheASkeyword is case-insensitive, but the convention is uppercaseAS. - Names are lowercase by convention. Docker matches stage names case-insensitively, but keeping one style avoids confusion.
- A name should describe the stage's job:
deps,build,test,runtime. - A name must be unique within the Dockerfile. Reusing a name is an error in current BuildKit.
- A stage can only refer to stages defined earlier in the file. A
COPY --fromthat points to a later stage fails.
The three things `--from` can point to
| Form | Example | Meaning |
|---|---|---|
| Stage name | `COPY --from=build /out/app /app` | An earlier stage in the same Dockerfile |
| Stage index | `COPY --from=0 /out/app /app` | The first stage, counting from zero |
| Image reference | `COPY --from=nginx:1.27 /etc/nginx/nginx.conf /tmp/` | Any image, pulled like a normal `FROM` |
If a name matches both a stage and an image, the stage wins. Avoid naming a stage alpine or node, because the name then shadows the image of the same name.
Stages can build on other stages
The base of a stage does not have to be a registry image. It can be an earlier stage:
FROM node:20-slim AS base
WORKDIR /app
COPY package*.json ./
FROM base AS deps
RUN npm ciThe deps stage starts from the filesystem and metadata that base produced. That includes the working directory, environment variables and copied files. Shared setup goes in one place, and the stages that follow inherit it.
A Dockerfile with several jobs
A single Dockerfile can describe more than the production image. This one has a test stage and a runtime stage, and both build on shared stages.
# syntax=docker/dockerfile:1
FROM node:20-slim AS base
WORKDIR /app
COPY package*.json ./
FROM base AS deps
RUN npm ci
FROM deps AS test
COPY . .
RUN npm test
FROM deps AS build
COPY . .
RUN npm run build
FROM base AS runtime
ENV NODE_ENV=production
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]The dependency relationships form a graph, not a line:
The test stage is a dead end. Nothing copies from it and nothing inherits from it. That matters for the next section.
Building one stage with `--target`
By default, docker build produces the last stage in the file. The --target flag tells it to produce a different stage:
docker build --target test -t myapp:test .
docker build --target build -t myapp:build .
docker build -t myapp:latest .The first command builds base, deps and test, and stops. The second builds base, deps and build. The third builds the last stage, runtime, and the stages it needs.
The image you get is the target stage, with everything that stage inherited. Layers from stages that are not in the target's ancestry are not part of it.
Which stages actually run
Docker 23.0 and later use BuildKit by default. BuildKit works out which stages the target depends on and skips the rest. The target depends on a stage if it uses it in FROM <stage> or COPY --from=<stage>, directly or through other stages.
For docker build -t myapp:latest . in the example, BuildKit runs base, deps, build and runtime. It does not run test. Unit tests are never run by the production build, even though the stage is in the same file.
The older classic builder behaves differently. It builds stages in file order up to the target, so it would run test too. If you are on an older Docker, or on a CI system that sets DOCKER_BUILDKIT=0, the same Dockerfile can behave differently. Use --progress=plain to see which steps actually execute:
docker build --progress=plain --target test -t myapp:test .Common uses for `--target`
Run tests in CI
docker build --target test -t myapp:test .
docker build -t myapp:latest .If the tests fail, the first command exits with a non-zero status and the pipeline stops. The second command reuses the cached base and deps layers, so it is not much slower than a build without the test step.
Debug a build stage
When a build step fails, or the compiled output looks wrong, you can build up to that stage and open a shell in it:
docker build --target build -t myapp:build .
docker run --rm -it myapp:build shThe build stage still has the source code, the dev dependencies and the compiler or bundler. The runtime image has none of those. This is also the quickest way to compare sizes, as shown in the docker image ls example from the measuring chapter.
Add a development stage
A dev stage can add tools you never want in production, such as a file watcher:
FROM deps AS dev
COPY . .
CMD ["npm", "run", "dev"]Developers build it with --target dev. Production builds ignore it because the last stage does not depend on it.
Keeping the default target safe
The default target is whichever stage is last in the file. This has two consequences.
- If you add a stage at the bottom, such as a
devstage, a plaindocker build .now produces that stage. Your production pipeline silently ships a development image. - If you reorder stages, the default changes without any error.
Two habits prevent this. Keep the production stage last. Better, always pass --target runtime explicitly in CI and deployment scripts, so the intent is visible in the command:
docker build --target runtime -t myapp:1.4.0 .An explicit target also documents the build for the next person reading the pipeline.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `target stage "tset" could not be found` | Typo in `--target`. | Match the name used in `FROM ... AS`. |
| `COPY --from=build` copies the wrong files after you add a stage | The Dockerfile uses a numeric index. | Use a stage name. |
| A `dev` image reaches production | The `dev` stage was added at the end of the file and no target was set. | Pass `--target runtime`, or move the production stage last. |
| Tests never run in a normal build | BuildKit skips stages that the target does not use. | Build `--target test` as its own step. |
| `from --from=builder: stage not found` | The referenced stage is defined after the `COPY`, or the name is misspelled. | Define stages before they are used. Check the spelling. |
Summary of the working model
FROM image AS namelabels a stage.COPY --from=nameandFROM nameboth refer to it.- A stage can start from a registry image or from an earlier stage.
--target namebuilds that stage and the stages it depends on. The result is an image of the target stage.- With BuildKit, unrelated stages are skipped. With the classic builder, stages run in file order up to the target.
- The default target is the last stage, so set
--targetexplicitly in automated builds.
Exercise
A Dockerfile defines the stages base, deps, test and runtime in that order. runtime copies files only from deps. A teammate adds a debug stage at the end of the file that starts FROM runtime AS debug and installs a shell and a profiler. After the change, a CI job that runs docker build -t myapp:release . pushes an image with the profiler in it. Why did that happen, what exact command change fixes it, and does this build run the test stage under BuildKit?
Show answer
With no --target, Docker builds the last stage in the file. Adding debug at the end made it the default target, so the release image is the debug image. The fix is docker build --target runtime -t myapp:release ., or moving debug above runtime. Under BuildKit the test stage does not run in either case, because neither runtime nor debug depends on it (neither copies from it or inherits from it). Tests need their own docker build --target test step.