15

The beginning of my docker file is below, I change the stuff after it often but never this part, but it takes a while to run, especially RUN apt-get -y install npm, can I cache the package download somehow? I looked at docker caching but I don't think that is what it does?

FROM ubuntu:20.04

RUN apt-get -y update
RUN apt-get -y install ruby
RUN apt-get -y install ruby-dev
RUN apt-get -y install gcc
RUN apt-get -y install make
RUN gem install compass
RUN apt-get -y install nodejs
RUN apt-get -y install npm
RUN apt-get -y install git
Fraser Langton
  • 471
  • 3
  • 12
  • 1
    what like you mean to make an image from this Dockerfile put it on docker hub and `FROM` from that? btw you should consolidate all them lines into a single RUN, else you're making a bunch of intermediate layers [*](https://stackoverflow.com/questions/39223249/multiple-run-vs-single-chained-run-in-dockerfile-which-is-better) – Lawrence Cherone Mar 25 '21 at 23:11
  • oh so I should make an image of those first lines and pull that, I get it, I can just have that image locally right? And I will condense those run lines – Fraser Langton Mar 25 '21 at 23:19
  • 1
    Does this answer your question? [How to share apt-package across Docker containers](https://stackoverflow.com/questions/52447375/how-to-share-apt-package-across-docker-containers) – Gino Mempin Mar 25 '21 at 23:41
  • Docker should cache all of this on its own. (The first `COPY` or `ADD` directive with changed files would break the layer caching, but you haven't shown any of those at all.) – David Maze Mar 26 '21 at 00:00

1 Answers1

17

This will store apt-get packages in the docker cache so they won't need to be re-downloaded. You need to be using buildkit.

# syntax=docker/dockerfile:1.3.1
FROM ubuntu

RUN --mount=target=/var/lib/apt/lists,type=cache,sharing=locked \
    --mount=target=/var/cache/apt,type=cache,sharing=locked \
    rm -f /etc/apt/apt.conf.d/docker-clean \
    && apt-get update \
    && apt-get -y --no-install-recommends install \
        ruby ruby-dev gcc

See this documentation for more details.

kdauria
  • 6,300
  • 4
  • 34
  • 53
  • Why `rm -f /etc/apt/apt.conf.d/docker-clean` ? – Peter VanderMeer Jul 06 '23 at 13:34
  • 1
    Nevermind, I found out why. [This](https://vsupalov.com/buildkit-cache-mount-dockerfile/) site explains it well. For others, essentially Docker deletes these cache files by default so they don't cause bloat in the resulting image. Except when we specify the mount, it automatically excludes them from the image (and we want to keep them in the cache for future builds) – Peter VanderMeer Jul 06 '23 at 13:47