Automate Docker Cleanup: A Shell Script That Saves Me 20 Minutes Every Week
Docker does not clean up after itself, and that is by design: images, containers, volumes, build cache, and networks all persist until you remove them. A small cron-driven shell script that runs docker system prune with explicit filters reclaims disk automatically and replaces the weekly manual sweep of docker ps -a and docker images. The working script is below, tested against Docker Engine 27.x on Ubuntu 24.04 and Debian 12.

What people assume Docker cleanup does versus what it actually does
The common assumption is that docker system prune wipes everything unused, so running it once solves the problem. In reality, the default prune is conservative: it removes stopped containers, dangling images, unused networks, and (with -a) all images not referenced by a container, but it skips volumes unless you pass --volumes, and it never touches build cache unless you ask. That gap is where disk fills up.
| Myth | Reality (Docker Engine 27.x) | What to run instead |
|---|---|---|
“docker system prune cleans everything” |
Volumes and build cache are excluded by default | docker system prune -a --volumes plus a separate docker builder prune |
| “Pruning removes images I am still using” | Images referenced by a running or stopped container are kept unless the container is removed first | Prune containers first, then images, then volumes |
“--volumes is safe to run blindly” |
It deletes named volumes not attached to any container, including database data | Filter with --filter label!=keep or exclude the volume by name |
| “Build cache clears with the image prune” | BuildKit cache lives separately and can exceed image size | docker builder prune --filter until=168h |
| “A cron job needs root” | Any user in the docker group can run prune |
Run as a dedicated user, not root |
Why the default prune leaves gigabytes behind on a busy host
BuildKit keeps intermediate layers and cache mounts that docker system prune does not report in its “Total reclaimed space” line, so a host can show tens of gigabytes used after a “successful” prune. According to the Docker Engine documentation, docker builder prune is a separate command with its own --filter flags, including until= for age-based cleanup. On CI runners and dev laptops that rebuild images daily, this cache is usually the largest single consumer.
The second trap is stopped containers. A container that exited with code 1 still holds its writable layer and any anonymous volumes. Pruning images with -a while those containers exist leaves orphaned layers you cannot see. This is the failure mode that costs people hours: you prune, disk usage barely moves, and you assume the command is broken.
The shell script that runs weekly without touching anything you need
The script below prunes in dependency order (containers, then images, then build cache, then volumes behind a label guard) and logs reclaimed bytes so you can prove it works. Save it as /usr/local/bin/docker-cleanup.sh and make it executable.
#!/usr/bin/env bash
# docker-cleanup.sh — Docker Engine 27.x, Bash 5.x
set -euo pipefail
LOG=/var/log/docker-cleanup.log
KEEP_LABEL="keep=true"
log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*" | tee -a "$LOG"; }
log "=== cleanup start ==="
docker system df | tee -a "$LOG"
# 1. Stopped containers older than 24h
docker container prune -f --filter "until=24h" | tee -a "$LOG"
# 2. Dangling images, then unused images older than 7 days
docker image prune -f | tee -a "$LOG"
docker image prune -a -f --filter "until=168h" | tee -a "$LOG"
# 3. BuildKit cache older than 7 days
docker builder prune -f --filter "until=168h" | tee -a "$LOG"
# 4. Volumes: refuse to touch anything labelled keep=true
docker volume ls -q --filter "label!=${KEEP_LABEL}" \
| xargs -r docker volume rm 2>/dev/null || true
# 5. Unused networks
docker network prune -f --filter "until=168h" | tee -a "$LOG"
log "=== cleanup done ==="
docker system df | tee -a "$LOG"
Now here is what it actually does. Step 1 removes containers that have been stopped for more than a day, which is the point at which a crashed container is almost certainly not coming back. Step 2 clears dangling images first (fast, safe) and then images unused for seven days. Step 3 is the one most people skip: docker builder prune --filter until=168h is documented in the Docker CLI reference and is the only way to reclaim BuildKit cache by age. Step 4 deletes volumes only if they lack the keep=true label. Step 5 clears networks older than a week, which matters on hosts that create per-branch compose networks.
How to schedule it with cron and verify it ran
A single cron entry running as a user in the docker group is enough; no root shell required. This is known to work on Ubuntu 24.04 and Debian 12 with the distribution Docker packages.
# /etc/cron.d/docker-cleanup
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 3 * * 0 docker /usr/local/bin/docker-cleanup.sh
The PATH line is not optional. Cron starts with a minimal environment, and docker living in /usr/bin is not guaranteed on every install. Omitting it is the second-most-common reason a cleanup job silently does nothing. After the first run, confirm with tail -n 40 /var/log/docker-cleanup.log and check that the two docker system df snapshots differ.

Which prune flags are safe to automate and which need a guard
Container, image, network, and build-cache pruning are safe to automate with until= filters because they only remove objects that are not running. Volume pruning is the exception: --volumes on docker system prune removes every anonymous and named volume not attached to a container, which includes database data from a stopped stack. The Docker documentation for docker system prune states this explicitly. Do not do this. Do this instead: label anything you care about with docker run --label keep=true, or in compose, labels: ["keep=true"], and filter on it as the script does.
What the failure mode looks like when the script goes wrong
The failure to watch for is a script that exits 0 while reclaiming nothing. set -euo pipefail catches most errors, but a prune with a filter that matches nothing returns success with zero bytes freed. Watch the log for consecutive runs where the second docker system df shows no change, then widen the until= window or check whether a stopped container is still holding layers. The second failure mode is cron running the script under a user not in the docker group: the first docker call fails with a permission error, set -e exits, and the log shows a single line. Add id -nG | grep -q docker as the first check if you want a louder failure.
Frequently asked questions about automating Docker cleanup
Does docker system prune -a delete images used by stopped containers?
No. An image referenced by any container, running or stopped, is retained until that container is removed. This is why the script prunes containers first with --filter until=24h and only then runs docker image prune -a.
How much disk does Docker build cache usually consume?
There is no fixed number, but on hosts that rebuild images daily the BuildKit cache commonly exceeds the size of the images themselves. docker system df -v reports a separate “Build cache” line, which is the figure docker system prune does not reduce.
Can this script run inside a container instead of on the host?
Yes, if you mount the Docker socket, but that grants the container root-equivalent control of the host daemon. For a weekly cleanup job, a cron entry on the host is the lower-risk option and needs no extra image to maintain.
The bottom line on automating Docker cleanup
A 20-line Bash script on a weekly cron replaces the manual sweep and reclaims the two things the default prune ignores: BuildKit cache and old images behind stopped containers. Start with the script above, label your persistent volumes keep=true before the first run, and check the log’s two docker system df snapshots after week one. If the numbers do not move, the problem is a stopped container holding layers, not the script.
Primary source: GNU Bash manual.
Related reading: How to Write Your First Bash Script: Beginner’s Guide with Examples.
If this helped, this next one will too: How to Fix npm ERR! code ERESOLVE Peer Dependency Conflict in 2026 Without Downgrading Node.