I have one multi stage dockerfile:
# build
FROM alpine:3.18.4 AS build
WORKDIR /src
RUN apk update
RUN apk add --no-cache git
RUN git clone https://github.com/app/app.git ./
RUN apk add --no-cache go
RUN go build -ldflags '-s -w'
# image
FROM alpine:3.18.4
COPY --from=build /src/app /usr/bin/
After that I expect to get two images but I get one image instead:
docker image build -t app:latest ./
docker image ls -a
REPOSITORY TAG IMAGE ID CREATED SIZE
app latest 001c1a4b00c8 50 minutes ago 40.8MB
Why I get only one image instead two images? Is it possible to get two image?
I read this: Docker: Multistage builds result in multiple images. But author got three images by default.
The documentation describes how multi-stage builds only output one image at the end. While you can integrate files from earlier stages into later stages using COPY --from=...
, only the final stage in the Dockerfile is used as the output image and the intermediate stages are ignored (but may remain in the internal build cache to speed up future builds).
You can still choose to output an intermediate stage if you specify it with --target
. For example with the Dockerfile you provided, --target=build
will stop the build after the build
stage completes, and the results of the build
stage will be used as the output image.
To output several intermediate stages, you can use docker build
several times, naming each --target
that you're interested in. You may also wish to use -t
to tag each stage-image with a unique name.