Search code examples
dockerdocker-multi-stage-build

How to use tagged intermediate image for final build?


I have created a multi-stage build.

  • Stage 1: use node:16.10-alpine to compile sources
  • Stage 2: use an alpine nginx image, copy build folder from first stage, move configuration, expose port, add entrypoint.

Here's the Dockerfile:

# Builder
FROM node:10.16-alpine AS builder

... # Do stuff

# Release
FROM nginx:1.16.0-alpine

COPY --from=builder /usr/src/app/build /usr/share/nginx/html

... # Do stuff

ENTRYPOINT [ ... ]

Pretty straight-forward, I'd say. I know that one you run docker build -t website:latest . it will create an intermediate image <none>, which is that builder image, which might be used later, if there were no changes to sources or package.json.

So, my thought was to tag the builder step something like this: docker build --target builder -t website-builder . and so that even if the sources change, it will just use the same tag and not (please correct me if I'm wrong) create other images.

If I run build with --target flag first and run build again without it doesn't use the builder.

To summarize:

  1. docker build --target builder -t website-builder . First Step
  2. docker build -t website:latest . Second Step

New <none> image was created which is the same as website-builder.

How can I achieve that the builder image is used by the 'Release' stage and rewritten, if changed? If that can't be done, what's the best-practice in this case? Is there one?

Thanks for sticking through. I appreciate any feedback or advice.


Solution

  • I think you may use:

    COPY --from=website-builder:latest .....