Daily Docker Prune with Systemd

| Shey Sewani | Toronto

I use Docker. I used to manually prune Docker every few weeks to keep it from eating up all my disk. Annoyed I eventually put it in cron, but, have you used cron? It wasn’t fun, and I just can’t anymore with cron. I was complaining about it on Mastadon and the adam12 showed me a better way: use systemd timers to schedule the prune. Here’s how it works: first, two files—one for the service, one for the timer.

The service file: /etc/systemd/system/docker-prune.service


[Unit]
Description=Daily Docker System Prune
Wants=docker.service
After=docker.service

[Service]
Type=oneshot
ExecStart=/usr/bin/docker system prune -f --filter "until=720h"

[Install]
WantedBy=multi-user.target

The timer file: /etc/systemd/system/docker-prune.timer


[Unit]
Description=Run Docker System Prune Daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

Enable the service and timer

sudo systemctl daemon-reexec
 sudo systemctl enable --now docker-prune.timer

Confirming it’s working

List active timers:

systemctl list-timers --all

Check the logs:

journalctl -u docker-prune.service

It runs once a day like it’s supposed to. The logs are easier to read, and the files are easier to edit. So yeah, no more cron.