Cleaning up the build host

Cleaning up after builds

When docker performs a built it caches each generated layer so that subsequent builds run faster as, if a layer has not changed and all earlier layers in the Dockerfile were taken from the cache then it will reuse that layer.

This is brilliant during development, but it can end up filling your disk due to old layers occupying space.

To solve this you need to periodically clean up old unused layers.

Manual process

The easiest way is to run the following commands every so often. These will remove any image not in active use by a running container.

1docker container prune -f
2docker image prune --all -f

Automatic process

The better way, more so if you run dedicated build hosts, is to set up a crontab to perform the cleanup periodically.

The following crontab is what I use:

150 * * * * docker container prune -f --filter "until=4h"
255 * * * * docker image prune --all -f --filter "until=4h"
359 * * * * docker volume prune -f

It runs every hour and removes any container or image if they are unused and are older than 4 hours old. This works well on both dedicated build servers and my local machine.