To cache or not to cache when installing OS packages?

The common wisdom, recommended even by a popular hadolint, is to always run package installs without caches and/or drop them.

However, reading about --mount=type=cache I get a sense that a following method may make more sense:

RUN --mount=type=cache,target=/var/log \
    --mount=type=cache,target=/var/cache,sharing=locked \
    --mount=type=cache,target=/var/lib/apt/lists,sharing=locked <<EOT
  set -eux
  . /etc/os-release
  if [ "$ID" = "alpine" ]; then
    apk update
    apk add <packages>
  elif [ "$ID" = "debian" ]; then
    rm -f /etc/apt/apt.conf.d/docker-clean
    echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
    apt-get update
    apt-get install -y --no-install-recommends <packages>
  fi
EOT

Even the official documentation in “caching apt packages” example suggests such approach. However, I am unable to find pros/cons for both approaches, beyond the caching approach being very verbose with mounts.

1 Like

I guess the “common wisdom” comes from the time when cache mounts didn’t exist or when buildkit was not the default builder. People using older Docker versions might need to enable buildkit or maybe even add the version of the Dockerfile syntax. I’m not sure, but I think that has to be below Docker CE v24.

The old way always works, but the new way should work on recent Docker versions.
Not in your example, but I can imagine cases when the cache folder is not so obvious, so people still need to run a command that clears the cache.