brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: docker build --target stops the build at one named stage

Docker
~/tips/tip-docker-build-target

FROM golang:1.26 AS build

Builds a multi-stage Dockerfile only up to the stage you name, for debugging or testing.

If your Dockerfile has several stages, you do not have to build all of them every time. --target builds up to the stage you name and ignores the rest.

The multi-stage docs use a small Go program: a stage named build compiles it, and a final stage copies the binary into scratch. Naming a stage is just AS after FROM:

FROM golang:1.26 AS build
WORKDIR /src
COPY . .
RUN go build -o /bin/hello ./main.go

FROM scratch
COPY --from=build /bin/hello /bin/hello
CMD ["/bin/hello"]

A normal build produces the small final image. To stop at the first stage instead:

docker build --target build -t hello:build .

The docs list the common uses: debugging one stage, or keeping a testing stage with test data or a debug stage with extra tools apart from the lean production stage. I like it for the moment a build fails halfway through a long Dockerfile, because you can build the stage before the failing one, start a shell in it with docker run -it --rm hello:build sh and try the command by hand.

An image built with --target is a normal image with whatever name you give it, so use a different tag from the real one (hello:build above), or you overwrite the final image with an intermediate stage. Naming the stage also makes COPY --from=build easier to read than a stage number.

Further reading: Multi-stage builds

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link