Prune dangling build cache
In this step, we will learn how to prune dangling build cache. Dangling build cache refers to build cache layers that are no longer associated with any named image. This can happen when you rebuild an image and a previous layer is replaced by a new one. Pruning dangling cache can help free up disk space.
First, let's modify our Dockerfile.cache
slightly to create some dangling cache. We will change the RUN
instruction.
Navigate to the ~/project
directory if you are not already there.
cd ~/project
Open the Dockerfile.cache
file for editing.
nano Dockerfile.cache
Change the RUN
instruction from:
RUN apt-get update && apt-get install -y --no-install-recommends curl
to:
RUN apt-get update && apt-get install -y --no-install-recommends wget
Save the file and exit the nano editor (Press Ctrl + X
, then Y
, then Enter
).
Now, let's rebuild the image with the same tag.
docker build -t myimage:cachetest -f Dockerfile.cache .
Observe the output. Docker will likely reuse the FROM
layer from the cache, but the RUN
instruction has changed, so it will execute that step again, creating a new layer. The previous layer created by the old RUN
instruction is now dangling build cache because it's no longer part of the myimage:cachetest
image.
To see the build cache, you can use the docker builder prune --dry-run
command, although it's not always easy to distinguish dangling cache specifically without more advanced tools or understanding of the buildkit output. A simpler way to see the effect is to prune the dangling cache and see the space reclaimed.
To prune only the dangling build cache, we use the docker builder prune
command with the --filter dangling=true
option.
docker builder prune --filter dangling=true
You will be prompted to confirm the action. Type y
and press Enter
.
WARNING! This will remove all dangling build cache.
Are you sure you want to continue? [y/N] y
The output will show the amount of space reclaimed. This space was occupied by the dangling build cache layers that were no longer needed.
By pruning dangling build cache, you can recover disk space that is no longer being used by any active image layers.