How to automatically cleanup (prune) docker images daily

Note: This will only remove docker images without a tag, but not all images not associated to a running or stopped container. See our post on How to automatically cleanup (prune) docker images daily in case this is not the desired behaviour. docker image prune provides an easy way to remove “unused” (i.e. untagged) docker images from a system and hence fixes or significantly delays docker eating up all your disk space on.

I created a systemd-timer based daily prune routine using TechOverflow’s Simple systemd timer generator.

Quick install using

example.sh
wget -qO- https://techoverflow.net/scripts/install-cleanup-docker.sh | sudo bash

This is the script which automatically creates & installs both systemd config files.

example.sh
#!/bin/sh
# This script installs automated docker cleanup via "docker image prune"
# onto systemd-based systems.
# It requires that docker is installed properly

cat >/etc/systemd/system/PruneDocker.service <<EOF
[Unit]
Description=PruneDocker

[Service]
Type=oneshot
ExecStart=/usr/bin/docker image prune -f
WorkingDirectory=/tmp
EOF

cat >/etc/systemd/system/PruneDocker.timer <<EOF
[Unit]
Description=PruneDocker

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target
EOF

# Enable and start service
systemctl enable PruneDocker.timer && sudo systemctl start PruneDocker.timer

To view logs, use

example.sh
journalctl -xfu PruneDocker.service

To view the status, use

example.sh
sudo systemctl status PruneDocker.timer

To immediately cleanup your docker images, use

example.sh
sudo systemctl start PruneDocker.service

Check out similar posts by category: Container, Docker