CloudesireDeveloper's Corner Blog Automatically remove unused Docker data with systemd

Automatically remove unused Docker data with systemd

We use Docker A LOT at Cloudesire, and working intensely with it can leave some cruft in /var/lib/docker.

Fortunately, the Docker CLI supports pruning, which works as a garbage collector for unused objects such as images, containers, volumes, and networks.

You can try it on a terminal with

$ docker system prune

WARNING! This will remove:
    - all stopped containers
    - all networks not used by at least one container
    - all dangling images
    - all build cache
Are you sure you want to continue? [y/N] y
Total reclaimed space: 3.145GB

Not bad!

I’d like to automate this though… Let’s configure a systemd timer to schedule pruning on a weekly basis.

systemd will look for user services inside ~/.config/systemd/user/, so let’s create it

mkdir -p ~/.config/systemd/user

Enter the new directory and create two files, docker-prune.service

Description=Prune unused Docker images

ExecStart=/usr/bin/docker system prune --force


and docker-prune.timer

Description=Prune unused Docker images weekly



start and enable our new timer

systemctl --user start docker-prune.timer
systemctl --user enable docker-prune.timer

systemd will cleanup Docker leftovers every week!

Source: Developers’ Corner Blog