Prune Docker Automatically with a Weekly Cron Job

Conan Mercer Site Reliability Engineer

Prune Docker Automatically with a Weekly Cron Job

17 Jun 2022 - Conan Mercer

Ever run out of space on your build server? Learn how to automatically prune docker images to free up space every week.

Automatic Docker Pruning

Recently I had an issue where my Linux-based build server was suddenly full to the brim. Not ideal when you want to build and push to production. The codebase utilizes Docker, and as it happens, Docker has a wonderful Prune command to assist in cleaning up its unused containers and images.

Taking Out the Bins

In Linux, the easiest way to schedule a weekly job is to set up a cronjob to execute the desired docker prune command, for example, the following command will force docker to prune all unused images:

docker image prune -f

docker image prune - tells Docker to Prune unused images
-f - tells Docker to force the Prune command without prompting the user

Next, we need to create a new file in the etc/cron.weekly/ folder:


cd /etc/cron.weekly
sudo nano docker-prune
The file should open, and allow us to add the desired prune command and inform the OS that this is a bash file (place the Bash Shebang at the top of the file)

#!/bin/bash
docker image prune -f
To save and close the file, hit Ctrl + O and then Ctrl + X

Schedule

This next part is important. We need to tell the OS to execute our cronjob by using the following command:

sudo chmod +x /etc/cron.weekly/docker-prune
All done. Docker will now execute this command every week.

Testing

To test out the command to see if it will execute correctly next time the cronjob runs, you can force the weekly Cron register to run with the following command:

run-parts /etc/cron.weekly