Sub topic 14
Scheduling Cleanup Safely
This chapter assumes you can run the prune commands from earlier chapters by hand and know which ones can delete data. It also assumes you can edit a crontab or a systemd unit on a Linux host. Here you will automate a conservative prune, keep it from damaging running work, and check that it keeps running.
What a scheduled prune should do
A prune you run by hand has a person watching it. You read the confirmation prompt, you know what you just built, and you can stop. A scheduled prune has none of that. It runs at 03:00 on whatever state the host is in, and nobody sees the result until the disk fills again or something goes missing.
So a scheduled cleanup should follow three rules:
- It removes only objects that are easy to recreate: stopped containers, dangling images, unused networks, and build cache.
- It removes only objects older than a set age, so it does not delete things from a job that is running right now.
- It never touches volumes.
The age limit and the exclusion of volumes are what make unattended pruning safe.
Choosing the command
The command from the previous chapter fits these rules:
docker system prune -f --filter "until=168h"The -f flag skips the confirmation prompt, which a script needs. The until=168h filter limits removal to objects created more than seven days ago. Because --volumes is not passed, volumes are left alone.
| Object | Removed by this command | Notes |
|---|---|---|
| Stopped containers | Yes, if older than 7 days | Running containers are never touched |
| Dangling images | Yes, if older than 7 days | Tagged images that no container uses are kept, because `-a` is not passed |
| Unused networks | Yes, if older than 7 days | Networks with attached containers are kept |
| Build cache | Yes, if older than 7 days | The next build may be slower |
| Volumes | No | Needs `--volumes`, so keep it out of schedules |
Do not add -a to a scheduled prune unless you accept re-pulling images. With -a, any image not used by a container is removed once it is older than the cutoff. That includes a base image you pulled yesterday for a build that has not run yet, if its creation date is old. The until filter checks when an image was created, not when it was pulled. An image built months ago and pulled this morning can therefore be removed on the next run.
You can protect objects with labels. If you label an image, container, or network with keep, a label filter excludes it:
docker system prune -f --filter "until=168h" --filter "label!=keep"The label!=keep filter removes only objects that do not carry the keep label. This helps with long-lived stopped containers or networks that you do not want to lose.
A cron entry that works
The entry from the spine is a good starting point:
0 3 * * 0 docker system prune -f --filter "until=168h"It runs every Sunday at 03:00. In practice it often fails silently, for three reasons:
- Cron uses a minimal
PATH, sodockermay not be found. Use the full path, which you can find withcommand -v docker. - The crontab belongs to a user. That user must be root or a member of the
dockergroup. Otherwise the command fails with a permission error on the Docker socket. - Cron discards output unless you redirect it or have local mail configured. Without a log you cannot tell whether the job ran.
A more reliable version is:
0 3 * * 0 /usr/bin/docker system prune -f --filter "until=168h" >> /var/log/docker-prune.log 2>&1Write to a path the cron user can write to. If you install this in root's crontab with sudo crontab -e, /var/log works.
Wrapping the command in a script
Once you want to record disk usage before and after, or prevent two runs from overlapping, a short script is easier to maintain than a long crontab line. Save this as /usr/local/bin/docker-cleanup.sh:
#!/usr/bin/env bash
set -euo pipefail
echo "=== Docker cleanup started: $(date -Is) ==="
echo "--- Disk usage before ---"
docker system df
docker system prune -f --filter "until=168h" --filter "label!=keep"
echo "--- Disk usage after ---"
docker system df
echo "=== Docker cleanup finished: $(date -Is) ==="Make it executable with sudo chmod 755 /usr/local/bin/docker-cleanup.sh. The set -euo pipefail line stops the script at the first error. The docker system prune output reports "Total reclaimed space", so the log shows what each run achieved.
Then schedule it with flock:
0 3 * * 0 /usr/bin/flock -n /var/lock/docker-cleanup.lock /usr/local/bin/docker-cleanup.sh >> /var/log/docker-cleanup.log 2>&1The -n option makes flock exit immediately if another run still holds the lock. This prevents a slow prune from overlapping the next one.
Using a systemd timer instead
On hosts that use systemd, a timer gives you logs in the journal and catches up after downtime. Create two units. The first, /etc/systemd/system/docker-cleanup.service, describes the job:
[Unit]
Description=Prune old Docker objects
After=docker.service
Requires=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/docker-cleanup.shThe second, /etc/systemd/system/docker-cleanup.timer, describes the schedule:
[Unit]
Description=Weekly Docker cleanup
[Timer]
OnCalendar=Sun *-*-* 03:00:00
Persistent=true
RandomizedDelaySec=30m
[Install]
WantedBy=timers.targetEnable it and check the next run time:
sudo systemctl daemon-reload
sudo systemctl enable --now docker-cleanup.timer
systemctl list-timers docker-cleanup.timer
journalctl -u docker-cleanup.service -n 50Persistent=true runs a missed job at the next boot, which cron does not do. RandomizedDelaySec spreads the start time, so a fleet of hosts does not prune at the same moment. Output from the script goes to the journal, so no log redirection is needed.
Failure modes to plan for
Even a conservative prune can cause trouble. These are the common cases:
- A build runs during the prune. Pruning build cache while a build is active can slow or fail that build. Schedule the job outside CI hours, or on CI runners that are idle at that time.
- A stopped container you wanted. A container that exited a week ago, such as a one-off database for debugging, is removed. Label it
keepor do not stop it. - Images that must be pulled again. On a host with a slow or rate-limited registry connection, removing old images costs time later. Keep
-aout of the schedule and check pull limits first. - Disk fills before the next run. A weekly prune cannot help if a build loop fills the disk in a day. Pair the schedule with log rotation, and run
docker system dffrom a monitoring check. - Silent failure. A changed
PATH, a removed user, or a stopped Docker daemon makes the job fail with no one noticing. Check the log or journal, and alert if the log has not changed in more than a week.
Testing before you trust it
Prune has no dry-run flag, so test the schedule in stages:
- Run the script by hand and read the output. Confirm the "before" and "after" numbers differ in the way you expect.
- List what the cutoff would match with the filter commands from the safety chapter, for example
docker ps -a --filter status=exitedanddocker image ls --filter dangling=true. - Start with a longer cutoff such as
until=720h(30 days). Shorten it once you know nothing important is lost. - After the first scheduled run, confirm that the log file or journal entry exists and shows a reclaimed-space line.
Exercise
A teammate proposes this crontab line to keep a build server clean: 0 2 * * * docker system prune -af --volumes. Name three problems with it for an unattended job, and write a safer replacement that runs weekly on Sunday at 03:00 and logs its output.
Show answer
Problems: (1) --volumes can delete data in volumes that no container currently references, such as a stopped database. (2) -a removes all images not used by a container, so base images for upcoming builds must be pulled again. (3) There is no until filter, so it can remove objects from a build or job that is running or just finished, and it runs daily. The line also uses a bare docker command with no full path and no log redirection, so a cron PATH problem would fail silently. A safer replacement: 0 3 * * 0 /usr/bin/docker system prune -f --filter "until=168h" >> /var/log/docker-prune.log 2>&1.