Change one line in requirements.txt and the whole pip install layer runs again, downloading everything from scratch.
BuildKit can keep a cache directory outside the image layers and mount it only during one RUN step.
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
The layer still reruns when its inputs change, but pip finds its wheels in the cache and skips the downloads. Nothing from the cache ends up in the final image, so the size stays the same.
For apt the docs add sharing=locked, because apt needs exclusive access to its data:
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
apt update && apt-get install -y gcc
It also works for npm, Go modules, cargo and anything else that has a download cache. You only change the target path.
The caveat: the cache lives on the machine that builds. A fresh CI runner starts empty, so you only gain on repeated builds on the same builder. The target path also differs per tool, so check where your package manager keeps its cache.
Further reading: Optimize cache usage in builds, On this site: a .dockerignore file makes builds faster and images smaller, On this site: share config between services with YAML anchors and x- fields