5.3.3.3 Targeted Stage Builds
A focused guide to Targeted Stage Builds, connecting core concepts with practical Docker and container operations.
Targeted stage builds use the --target flag to build only up through a specific named stage in a multi-stage Dockerfile, stopping before any later stages execute, useful for producing an intermediate artifact or image without needing to complete the entire defined build sequence.
Building Only a Specific Stage
The --target flag tells docker build to stop after the specified stage completes, ignoring any stages that would normally follow it.
FROM node:20 AS dependencies
COPY package*.json ./
RUN npm install
FROM dependencies AS test
COPY . .
RUN npm test
FROM dependencies AS build
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
docker build --target test -t myapp:test .
This builds only through the test stage, never executing the build stage or the final nginx stage at all.
Why Targeted Builds Are Useful
Being able to build just one stage in isolation supports workflows where different stages serve genuinely different purposes — running tests as a CI check, producing a debug-friendly intermediate image for troubleshooting — without needing to also produce the full final image every time.
docker build --target test -t myapp:test .
docker run --rm myapp:test
Producing Multiple Distinct Images From One Dockerfile
Combining targeted builds with different tags allows a single Dockerfile to produce several genuinely useful, distinct images, each corresponding to a different stage's purpose.
docker build --target build -t myapp:builder .
docker build -t myapp:latest .
Why Targeted Stage Builds Matter
The --target flag significantly extends what a single, well-structured multi-stage Dockerfile can provide, supporting multiple distinct build outcomes from one shared definition rather than requiring entirely separate Dockerfiles for each variation.