Behind every efficient build lies an invisible ally: the cache.
When it comes to building container images, Docker and BuildKit are great tools.
Docker provides the platform, BuildKit the engine.
Together they powers the container image build process.
But to make the most of them, it’s essential to understand how their caching mechanisms work.
This is what we are going to see in this tutorial.
GitHub for this tutorial
Environment
| Component | Version or configuration |
|---|---|
| Docker Client | 29.1.3 |
| Docker Server (engine) | 29.1.3 |
| BuildKit | 0.26.2 |
| Distribution | Ubuntu 24.04 |
Part 1 - The basic concepts
Before diving into the cache process, let’s see how a Dockerfile builds Docker image.
To understand how an image is built, we need to distinguish between two concepts:
- Stage: a build step starting with a
FROMinstruction. - Layer: a set of filesystem modifications produced by an instruction such as
RUN,COPYorADD.
The FROM instruction
Let’s have a look at this example:
FROM ubuntu:24.04 AS initial
The FROM instruction tells Docker which image to use as the starting point.
But even if this instruction starts a stage, it does not itself create a layer.
Here:
ubuntu:24.04is the base image.AS initialnames the first stageinitial(it can be any name).
Instructions that create layers
Let’s add a few instructions to our Dockerfile:
FROM ubuntu:24.04 AS initial
RUN apt-get update
RUN apt-get install -y curl
COPY script.sh /usr/local/bin/script.sh
In this case, the RUN and COPY instructions modify the filesystem, so each one creates a new layer.
The result can be represented as follows:
Stage: initial
│
├── Base image: ubuntu:24.04
│ ├── Base layer 1
│ ├── Base layer 2
│ └── Base layer ...
│
├── Layer 1: RUN apt-get update
├── Layer 2: RUN apt-get install -y curl
└── Layer 3: COPY script.sh /usr/local/bin/script.sh
The Ubuntu image provides the base layers.
Other instructions add their own layers on top of this image.
A Dockerfile with multiple stages
A Dockerfile can contain multiple stages, so each starting with a FROM instruction.
This is, in general, useful when you want to separate the build stage from the runtime one.
- A first stage to install build tools and compile the application.
- A second stage to create a smaller final image containing only the application and what it needs to run.
For example:
# Image 1: intermediate build stage
FROM ubuntu:24.04 AS initial
RUN apt-get update
RUN apt-get install -y build-essential
COPY source.c /src/source.c
RUN gcc /src/source.c -o /app
# Image 2: runtime stage
FROM ubuntu:24.04 AS final
COPY --from=initial /app /app
CMD ["/app"]
In this snippet:
- The first
FROMinstruction starts theinitialstage (the build phase). - The
RUNandCOPYinstructions add layers to that stage. - The second
FROMinstruction starts a new stage calledfinal. - The
COPY --from=initialinstruction copies the compiled application from theinitialstage into thefinalstage.
At the end, the final image contains the Ubuntu base image and the compiled application, but not the build tools or source code.
This is the main benefit of multi-stage builds: keeping build-time tools and dependencies out of the final image.
Part 2 - Docker Cache
What is the Docker cache?
As we previously saw, when Docker builds an image, it executes the instructions defined in the Dockerfile.
To avoid repeating the same work, during subsequent builds, Docker uses a build cache.
For example:
FROM ubuntu:24.04
RUN apt-get update
RUN apt-get install -y curl
If the same Dockerfile is built again without any relevant changes, Docker can reuse the cached results instead of executing the instructions again.
And during the new build output, cached instructions will be marked with CACHED, like this:
=> CACHED [2/3] RUN apt-get update
=> CACHED [3/3] RUN apt-get install -y curl
This can significantly reduce build time.
Let’s consider a new instruction:
COPY script.sh /usr/local/bin/script.sh
If we change the content of script.sh, the cache will be invalidated.
However, even if the source file remains unchanged, changing the destination path will also invalidate the cache.
Example:
COPY script.sh /usr/local/bin/script2.sh
In this case, the cache is also invalidated and the build is launched again because script.sh has become script2.sh in the destination path.
Furthermore, note that comments are not taken into account by Docker build cache.
They can therefore be modified or removed between builds without invalidating the cache.
Cache invalidation and instruction order
Changing an instruction in the Dockerfile invalidates the cache for that command.
But it also invalidates all subsequent instructions in the same stage.
So they have to be rebuilt as well.
Example:
FROM ubuntu:24.04
# Changes frequently
COPY target/build/app /run/app
RUN apt-get update
RUN apt-get install -y build-essential
Whenever a relevant file changes, in the build context, the COPY instruction may be invalidated.
As a result, the subsequent RUN instructions may also need to execute again.
A better approach is to place instructions that change less frequently before instructions that change more frequently.
For example:
FROM ubuntu:24.04
RUN apt-get update
RUN apt-get install -y build-essential
# Changes frequently
COPY target/build/app /run/app
Now, changing application files does not invalidate the earlier installation instructions (the RUN apt-get ones).
Cache busting and –no-cache option
Sometimes, you may want Docker to execute an instruction again even if its previous result is available in the cache.
There are two common approaches.
Method 1: Cache busting with a build argument
You can use an ARG instruction to introduce a value that changes between builds.
For example:
FROM ubuntu:24.04
ARG CACHE_BUST=1
RUN echo "Building with cache key: ${CACHE_BUST}" \
&& apt-get update
Build the image:
docker build --build-arg CACHE_BUST=1 -t my-image .
Then change the argument:
docker build --build-arg CACHE_BUST=2 -t my-image .
Because the argument value has changed, Docker invalidates the cache for the affected RUN instruction and subsequent instructions.
Method 2: Disabling the build cache with --no-cache
You can also disable the use of the build cache for a build with the --no-cache option:
docker build --no-cache -t my-image .
With this option, Docker executes the build instructions again instead of reusing cached results.
Build cache and cache mounts
BuildKit provides several caching mechanisms.
In particular, we need to distinguish between two concepts.
The regular build cache
For example:
RUN apt-get update && apt-get install -y tree
If BuildKit determines that the instruction has not changed between two builds, it can reuse the previously built layer without executing APT again.
But if the RUN instruction has changed, then the command will be rebuilt from scratch.
This is the default behavior of the regular build cache.
Cache mounts
BuildKit provides another type of cache: the cache mount.
We need, in this case, to write explicitly an option at a beginning of an instruction:
RUN \
--mount=type=cache,target=/path \
...
Unlike the regular build cache, the contents of a cache mount are intended to be reused by instructions across multiple builds.
This means that even when a regular build cache is invalidated, a cache mount can still provide data retained from previous builds.
That’s the main purpose of cache mounts.
Part 3 - The Dockerfile
In order to check that everything we said previously is true, we are going to test it with a Dockerfile.
Different tools will help us to visualize it as, indeed, every tool has its own behavior with the cache mount.
BuildKit preserves files in a directory, but the relevant tool decides how to use them.
Examples:
aptstores package archives and indexes.pipstores downloaded Python packages.weststores Git repositories.ccachestores compilation results.
BuildKit provides persistence, each tool manages its own cache.
Let’s start by describing the tools
APT
APT is the Ubuntu package manager.
One important aspect of our experiment concerns APT behavior.
In Ubuntu images, a configuration file named docker-clean may trigger the cleanup of downloaded files after APT operations:
/etc/apt/apt.conf.d/docker-clean
So, to preserve downloaded archives, it’s necessary to remove this file and create a dedicated configuration.
Here are the commands to add to our Dockerfile:
RUN rm -f /etc/apt/apt.conf.d/docker-clean \
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' \
> /etc/apt/apt.conf.d/keep-cache
This configuration must be applied before installing packages, so before the RUN instruction that uses the cache mount option.
For APT, we use two mounts:
RUN \
--mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
apt-get update \
...
/var/cache/apt:- allows APT’s downloaded files to be preserved, including
.debpackages.
- allows APT’s downloaded files to be preserved, including
/var/lib/apt:- allows APT’s package index data to be preserved.
Cache mounts are only used during the image build, so their contents are not included in the final image.
Note that these are the default paths used by APT.
Specifying other paths won’t work unless APT is configured to use them.
Moreover, in our cache mounts, we use this parameter:
sharing=locked
It prevents multiple builds from using the same cache simultaneously, much like a mutex.
If another build needs to use the cache, it must wait until the cache is released.
ccache
ccache is a cache tool designed for C and C++ compilation.
It checks whether the result of a compilation is already available.
RUN --mount=type=cache,target=/root/.cache/ccache,sharing=locked \
...
Python virtual environment (venv) and pip cache
The venv and the pip cache are two different directories, and they serve completely different purposes.
- The venv contains the installed Python software, ready to be used.
- The pip cache contains downloaded or locally built files that pip can reuse during future installations.
Creating the venv
In our Dockerfile, we create an independent Python virtual environment in /opt/.venv:
RUN python3 -m venv /opt/.venv
It’ll create the following directory structure (especially the bin/ folder):
/opt/.venv/
├── bin
│ ├── python -> python3
│ ├── python3 -> /usr/bin/python3
│ └── python3.12 -> python3
├── include
│ └── python3.12
├── lib
│ └── python3.12
│ └── site-packages
├── lib64 -> lib
└── pyvenv.cfg
8 directories, 4 files
But it does not activate it, instead we add its bin/ directory to the PATH.
ENV PATH=/opt/.venv/bin:${PATH}
This allows us to use the executables installed in the virtual environment directly, without activating it explicitly.
The pip cache
In our Dockerfile, we have:
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
pip install west
/root/.cache/pip-> BuildKit cache: stores reusable files that can speed up future installations./opt/.venv-> Image filesystem: contains West and its dependencies, installed and ready to use.
West
West is the tool used to manage projects and modules in a Zephyr workspace.
We distinguished between two operations:
west init: initializes a workspace from the manifest repository.west update: retrieves or updates module projects defined in the manifest.
west init
Our instruction is:
RUN GIT_TRACE=1 \
GIT_CURL_VERBOSE=0 \
west init \
-o=--progress \
-m https://github.com/zephyrproject-rtos/zephyr \
--mr v4.4.2 \
/opt/zephyrproject
In this snippet, west init uses the Docker layer cache, but to keep things simple, does not have a dedicated cache mount.
west update
We need to specify which Zephyr project to update and download.
Otherwise it will update all projects available in the manifest, which can take ages.
So we chose CMSIS (Common Microcontroller Software Interface Standard), a module to help develop Arm Cortex-M systems.
Feel free to use the one of your choice (it’s for the demonstration only).
We used a cache mount with an arbitrary cache directory as the West 1.5.0 version provides the --auto-cache option:
RUN --mount=type=cache,target=/root/.cache/west-git,sharing=locked \
cd /opt/zephyrproject \
&& west update --auto-cache /root/.cache/west-git cmsis
The --auto-cache option allows West to create and reuse bare Git repositories.
Bare Git repositories store Git objects and references without a working tree.
West can reuse these repositories when fetching projects, avoiding repeated downloads of the same Git data.
Part 4 - The build script
Docker stages and build targets
FROM ubuntu:24.04 AS apt-stage
FROM apt-stage AS ccache-stage
FROM apt-stage AS pip-stage
FROM pip-stage AS west-stage
The names apt-stage, ccache-stage, pip-stage and west-stage are stage names.
These names can be names of your choice.
We can build the stage pip-stage by using directly its stage name:
docker build --target pip-stage .
Docker then builds apt-stage and pip-stage because they are linked, but not the other independent stages.
Without --target, Docker builds the last stage in the Dockerfile as default final image.
But to optimize the process, we’ll use the following script:
build_image.sh
Its purpose is to:
- select the target;
- pass the cache number;
- build the image;
- display the total build time.
Usage:
./build_image.sh apt-stage BUST=1
./build_image.sh pip-stage BUST=1
./build_image.sh west-stage BUST=1
./build_image.sh ccache-stage BUST=1
./build_image.sh all BUST=1
The second argument is a cache-busting value (BUST), short for the CACHE_BUST variable inside the Dockerfile.
Changing this value invalidates the build cache for the corresponding stage, forcing it to run again.
For example:
./build_image.sh pip-stage BUST=1
./build_image.sh pip-stage BUST=2
./build_image.sh pip-stage BUST=3
However the cache mount is not deleted when this value changes.
Summary of the tests
| Cache | Directory | Result |
|---|---|---|
| APT archives | /var/cache/apt |
Validated |
| APT indexes | /var/lib/apt |
Validated |
| ccache | /root/.cache/ccache |
Validated |
| pip | /root/.cache/pip |
Validated |
| West Git | /root/.cache/west-git |
Validated for CMSIS |
The tests confirmed that BuildKit mounts make it possible to preserve data from tools across multiple builds.
Conclusion
We have achieved our main objective.
We are now sure that Docker and BuildKit provide at least two types of caching mechanisms:
- Build cache allows Docker to reuse the results of previous instructions, avoiding unnecessary rebuilds.
- Cache mounts provide persistent storage that can be reused across multiple builds, even when the regular build cache is invalidated.
BuildKit provides the persistence mechanism, while the tools themselves determine how cached data is stored and reused.
Well done, you’ve made it.