Automatically clearing docker desktop build cache

Docker
Logo

Özgür Sargut

Published Jul 06, 24

·

Last Updated Jul 06, 24

Ever since i started using a lot of docker compose files for local development my build cache size started going through the roof.

I was fixing it by clearing the who cache by hand but that's boring so here is an article on how to automate it 😉.

Disclaimer i am running debian 12 but you can do the same on a mac.

Doing it manually first so we know what we are doing

First of all lets see how much space we can reclaim

docker builder du

After this command you should see the total build cache used the total amount of space that reclaimable.

Here is the command to clear the docker build cache

docker builder prune

This command can take a while depending on the space that we are reclaiming.

Automating the process

So since we can clear the cache by hand lets just put the prune command into a file and run it with cron on a schedule.

Making the file

I like using ~/bin for user scripts but you might not have it in path. So either add ~/bin to path or use ~/.local/bin

touch ~/bin/docker-gc.sh
or
touch ~/.local/bin/docker-gc.sh

Add the contents for the file using your preferred editor (we need the --force here because prune command asks for confirmation and force flag disables that)

#!/bin/bash
# Run Docker Garbage Collection
docker builder prune --force

Make sure the files is executable

chmod +x ~/bin/docker-gc.sh
or
chmod +x ~/.local/bin/docker-gc.sh

Setup the cron job

crontab -e

And you add the desired interval for the script to run(mine runs at 3 every sunday).

You can use this website to generate the cron to your desired interval (https://it-tools.tech/crontab-generator)

0 3 * * 0 ~/bin/docker-gc.sh

That's it now you have lots of space.

Thank you for reading.