Install apt packages in docker via build step and copy

Viewed 1359

When you have a complicated RUN apt-get install section that you reuse over multiple docker images, what is the best way to reuse it?

The options that I think we have are

  • copy-paste the RUN command n times across your Dockerfiles (this is what I do today)
  • make a docker image and use it as a build step + COPY --from=builder... (this is what I wan't, but I don't konw how to do it).

I am thinking of something like this:

  1. Dockerfile with reusable apt install command, tagged as my-builder-img:
FROM debian:buster
RUN ... apt-get install ...
  1. Dockerfile that reuses that complicated install:
FROM my-builder-img as builder
#nothing here
FROM debian:buster
COPY --from=builder /usr/bin:/usr/bin # (...???)

TL;DR how to reuse apt-get install from a previus image onto a new image.

1 Answers

You just use the image you put all the packages in directly.

Multi-stage builds shine when you are creating an artifact and copying that to a new image. If you are just installing packages those will exist in the image.

Dockerfile with packages you want:

FROM debian:buster
RUN ... apt-get install ...

Tag it as my-image.

Now, just use that image in other Dockerfiles and the packages installed will be available.

FROM my-image:latest
# other directives...
Related