Build a Docker Cleanup Helper
This project builds dockerclean.sh, a script that finds the Docker objects nobody uses any more (stopped containers, leftover images and, if you ask for it, unused volumes), shows how old they are, and removes them. It is safe by default: without the -y option it only shows what it would remove. It never touches a running container or an object that is in use, it only removes objects that have been idle for a minimum time, and it treats volumes, which hold data, as an explicit opt-in.
Lesson 175 introduced Bash scripts for Docker. This project uses what you learned there and adds three ideas that every cleanup tool needs: a dry-run mode, an age limit, and error handling for each removed object.
What the Script Should Do
- Check that Docker is installed and that the daemon answers, and stop with a clear message otherwise.
- Show the Docker disk usage before and after, using
docker system df. - Find three kinds of candidates: stopped containers, dangling images and (with
-v) unused volumes. - Filter by age (
-o HOURS): an object is only removed when it has been unused for at least that long. - Dry run by default: print
would remove ...for every candidate and change nothing. - Remove the candidates with
-y, one by one, and report each success or failure. - Exit with status 1 if any removal failed.
Which Objects Are Safe to Remove
| Object | Candidate when | Why it is safe |
|---|---|---|
| Container | Its status is exited, created or dead | It is not running. Removing it deletes its writable layer (data written inside the container) and its logs |
| Image | It is dangling: it has no name and no tag | When you rebuild myapp:latest, the previous image loses its tag and stays on disk as a dangling image |
| Volume | It is dangling: no container refers to it | Nothing is using it right now. It may still contain data you want, so it needs -v |
A few terms matter here. An image is the read-only template a container starts from, and it consists of layers. A volume is storage managed by Docker that lives outside the container, typically used for databases. Dangling means "has lost its reference": an image without a tag, or a volume without a container.
The script does not remove tagged images that are simply not used at the moment (docker image prune -a does that). Those can be useful later, for example the base image of your next build, and downloading them again costs time and bandwidth.
Design Decisions
Dry Run by Default
A cleanup tool deletes data, so the careful behaviour has to be the default. The variable apply is 0 unless the user passes -y. Everything else in the script is written once and works in both modes: the function that handles a candidate prints what it found, and only calls docker ... rm when apply is set.
if (( ! apply )); then
say " would remove $kind $label ($note)"
return 0
fi
This pattern (preview first, act when asked) is the same one used by the file renamer in lesson 196. Whoever runs the script can look at the list, and only then repeat the same command with -y added.
Docker Output Formats
docker normally prints tables for humans. The --format option takes a Go template and prints exactly the fields you ask for, which is much easier to parse in a script:
docker container ls -a --filter status=exited --format '{{.ID}}|{{.Names}}|{{.Image}}'
Expected output (with the test data used later in this lesson):
a1b2c3|old-migration|python:3.12
b2c3d4|test-db|postgres:16
A vertical bar separates the fields. The script reads each line with IFS='|' read -r id name image, which splits at the bar. The bar is a good delimiter because it cannot appear in an image or container name. The --filter options select objects by state in the Docker daemon, so the script never receives the running containers at all.
Measuring the Age of an Object
Docker prints times in the ISO 8601 format, for example 2026-11-20T10:00:00.123456789Z. GNU date -d understands it and converts it to seconds since 1970, and a subtraction gives the age:
age_hours() {
local t
t=$(date -d "$1" +%s 2>/dev/null) || { echo 0; return; }
echo $(( (now - t) / 3600 ))
}
If date cannot parse the text, the function prints 0, so the object counts as brand new and is kept. When in doubt, a cleanup script must keep the object.
For a container, "unused" means time since it stopped. The script reads two values with one inspect call:
read -r finished created < <(docker container inspect --format '{{.State.FinishedAt}} {{.Created}}' "$id" </dev/null)
[[ $finished == 0001-* ]] && finished=$created
A container that was created but never started has the special finish time 0001-01-01T00:00:00Z, which would look 2000 years old. The second line replaces it with the creation time. Note that the test [[ $finished == 0001-* ]] uses a pattern, as in lesson 69. For an image the script uses its creation time. Docker does not record when a volume was last used, so the age limit cannot be applied to volumes. This is the reason that volumes need their own switch and the output says age not recorded for them.
Protecting the Loop's Input
The candidates are read with while read ... done < <(docker ...). Inside the loop the script runs more docker commands. Any command that reads from standard input would also read from the same input as read, and silently swallow the lines that are still waiting, so the loop would stop early with no error. Redirecting </dev/null for every docker command inside the loop prevents this. This is a standard defence in loops that read a file or a command's output (lesson 114), and it costs nothing.
Counting With Care
The function handle updates the counters found, removed and failed. It is called directly from the loops, and not inside $( ), so the counters are changed in the current shell (the same rule as in lessons 93 and 197). The while loops get their input through process substitution (< <(...)) instead of a pipe for the same reason: a loop at the right side of a pipe runs in a subshell, and the counters would be lost.
Separating Messages and Errors
The say function prints a message unless -q was given. Failures to remove an object are additionally written to standard error in quiet mode, so a scheduled job that has a problem is not silent:
(( quiet )) && printf '%s: could not remove %s %s\n' "$PROG" "$kind" "$label" >&2
The Complete Script
#!/usr/bin/env bash
#
# dockerclean.sh - find (and optionally remove) unused Docker objects
#
# Usage: dockerclean.sh [-o HOURS] [-v] [-y] [-q]
#
# Without -y the script only SHOWS what it would remove (dry run).
#
# Options:
# -o HOURS only touch objects that have been unused for at least HOURS hours
# (default: 24)
# -v also include unused volumes (volumes hold data; off by default)
# -y really remove the objects found
# -q print only the summary line
# -h show this help
#
# Candidates: stopped containers, dangling images (untagged layers left over
# from rebuilds) and, with -v, volumes that no container uses. Running
# containers and images or volumes in use are never touched.
#
# Exit status: 0 done (or dry run finished), 1 at least one removal failed,
# 2 usage error, 3 Docker is not reachable.
set -euo pipefail
export LC_ALL=C
readonly PROG=${0##*/}
usage() { sed -n '3,22s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit "${2:-2}"
}
hours=24 volumes=0 apply=0 quiet=0
while getopts ':o:vyqh' opt; do
case $opt in
o) hours=$OPTARG ;;
v) volumes=1 ;;
y) apply=1 ;;
q) quiet=1 ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ $hours =~ ^[0-9]+$ ]] || die "-o needs a whole number of hours"
command -v docker >/dev/null || die "docker is not installed" 3
docker info >/dev/null 2>&1 || die "cannot reach the Docker daemon (is it running? are you in the docker group?)" 3
now=$(date +%s)
min_age=$(( hours * 3600 ))
found=0 removed=0 failed=0
say() { (( quiet )) || printf '%s\n' "$1"; }
# age_hours TIMESTAMP - print the age in whole hours of an ISO 8601 time stamp.
# Docker prints times such as 2026-11-20T10:00:00.123456789Z.
age_hours() {
local t
t=$(date -d "$1" +%s 2>/dev/null) || { echo 0; return; }
echo $(( (now - t) / 3600 ))
}
# handle KIND ID LABEL SECONDS - report one candidate and remove it if allowed.
# SECONDS is the time the object has been unused, or -1 when Docker does not
# record it (volumes). The docker commands read /dev/null, so that they can
# never swallow the lines the calling "while read" loop is still waiting for.
handle() {
local kind=$1 id=$2 label=$3 secs=$4 note
if (( secs < 0 )); then
note="age not recorded"
elif (( secs < min_age )); then
say " keep $kind $label (unused for only $(( secs / 3600 )) h)"
return 0
else
note="unused for $(( secs / 3600 )) h"
fi
found=$((found + 1))
if (( ! apply )); then
say " would remove $kind $label ($note)"
return 0
fi
if docker "$kind" rm -- "$id" >/dev/null 2>&1 </dev/null; then
removed=$((removed + 1))
say " removed $kind $label"
else
failed=$((failed + 1))
say " FAILED $kind $label (still in use?)"
(( quiet )) && printf '%s: could not remove %s %s\n' "$PROG" "$kind" "$label" >&2
fi
}
say "Docker disk usage before:"
say "$(docker system df | sed 's/^/ /')"
say ""
(( apply )) && say "Mode: REMOVE objects unused for $hours h or more" \
|| say "Mode: DRY RUN (nothing is removed; add -y to remove)"
say ""
say "Stopped containers"
while IFS='|' read -r id name image; do
[[ -z $id ]] && continue
read -r finished created < <(docker container inspect --format '{{.State.FinishedAt}} {{.Created}}' "$id" </dev/null)
# a container that never ran has the finish time 0001-01-01: use its creation time
[[ $finished == 0001-* ]] && finished=$created
handle container "$id" "$name ($image)" $(( $(age_hours "$finished") * 3600 ))
done < <(docker container ls -a --filter status=exited --filter status=created --filter status=dead \
--format '{{.ID}}|{{.Names}}|{{.Image}}')
say ""
say "Dangling images"
while IFS='|' read -r id size; do
[[ -z $id ]] && continue
created=$(docker image inspect --format '{{.Created}}' "$id" </dev/null)
handle image "$id" "$id ($size)" $(( $(age_hours "$created") * 3600 ))
done < <(docker image ls --filter dangling=true --format '{{.ID}}|{{.Size}}')
if (( volumes )); then
say ""
say "Unused volumes (their data cannot be recovered)"
while read -r vol; do
[[ -z $vol ]] && continue
# volumes carry no usage time, so the -o age cannot be applied to them
handle volume "$vol" "$vol" -1
done < <(docker volume ls --filter dangling=true --format '{{.Name}}')
fi
say ""
if (( apply )); then
printf '%s: removed %d object(s), %d failed\n' "$PROG" "$removed" "$failed"
say ""
say "Docker disk usage after:"
say "$(docker system df | sed 's/^/ /')"
else
printf '%s: dry run, %d object(s) could be removed\n' "$PROG" "$found"
fi
(( failed == 0 ))
Testing Without Changing a Real System
The test machine for this lesson has the Docker client but no running Docker daemon, and a cleanup script is not something to try for the first time on a real server. The tests therefore use a fake docker program placed first in the PATH (lesson 186). It reads its "objects" from small text files and deletes lines from them when asked to remove something. One container, named stuck-job with the ID busy1, always refuses to be removed, which simulates an object that is still in use:
#!/usr/bin/env bash
# fake docker for tests; objects live in files under $DOCKER_STATE
S=${DOCKER_STATE:?}
[[ ${DOCKER_DOWN:-0} == 1 ]] && { echo "Cannot connect to the Docker daemon" >&2; exit 1; }
case $1 in
info) exit 0 ;;
system) cat "$S/df.txt" ;;
container)
case $2 in
ls) cat "$S/containers.txt" ;;
inspect) id=${@: -1}; grep "^$id " "$S/c_inspect.txt" | cut -d' ' -f2- ;;
rm) id=${@: -1}; [[ $id == busy1 ]] && { echo "in use" >&2; exit 1; }; sed -i "/^$id|/d" "$S/containers.txt"; echo "$id" ;;
esac ;;
image)
case $2 in
ls) cat "$S/images.txt" ;;
inspect) id=${@: -1}; grep "^$id " "$S/i_inspect.txt" | cut -d' ' -f2- ;;
rm) id=${@: -1}; sed -i "/^$id|/d" "$S/images.txt"; echo "$id" ;;
esac ;;
volume)
case $2 in
ls) cat "$S/volumes.txt" ;;
rm) id=${@: -1}; sed -i "/^$id\$/d" "$S/volumes.txt"; echo "$id" ;;
esac ;;
esac
The test data contains five stopped containers (idle for 200, 5, 100, 72 and 30 hours), three dangling images (idle for 500, 3 and 48 hours) and two volumes. Because the fake docker system df prints fixed numbers, the "before" and "after" tables below are identical in this test. On a real system the second table shows the space that was freed.
Running the Cleanup
Dry Run
$ ./dockerclean.sh -v
Docker disk usage before:
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 14 6 3.42GB 1.87GB (54%)
Containers 9 3 212MB 148MB (69%)
Local Volumes 5 2 1.1GB 640MB (58%)
Build Cache 31 0 980MB 980MB
Mode: DRY RUN (nothing is removed; add -y to remove)
Stopped containers
would remove container old-migration (python:3.12) (unused for 200 h)
keep container test-db (postgres:16) (unused for only 5 h)
would remove container stuck-job (alpine:3.20) (unused for 100 h)
would remove container never-started (nginx:1.27) (unused for 72 h)
would remove container build-tmp (node:22) (unused for 30 h)
Dangling images
would remove image sha256:9f1a (412MB) (unused for 500 h)
keep image sha256:7c2b (88MB) (unused for only 3 h)
would remove image sha256:1d3e (1.2GB) (unused for 48 h)
Unused volumes (their data cannot be recovered)
would remove volume pgdata_old (age not recorded)
would remove volume cache_tmp (age not recorded)
dockerclean.sh: dry run, 8 object(s) could be removed
- The default age limit is 24 hours.
test-dbstopped only five hours ago, so it is kept: someone may be debugging it right now. never-startedwas created 72 hours ago and never run, so its creation time was used.- The summary says could be removed. Nothing has changed.
A Stricter Age Limit
$ ./dockerclean.sh -o 100
...
Stopped containers
would remove container old-migration (python:3.12) (unused for 200 h)
keep container test-db (postgres:16) (unused for only 5 h)
would remove container stuck-job (alpine:3.20) (unused for 100 h)
keep container never-started (nginx:1.27) (unused for only 72 h)
keep container build-tmp (node:22) (unused for only 30 h)
Dangling images
would remove image sha256:9f1a (412MB) (unused for 500 h)
keep image sha256:7c2b (88MB) (unused for only 3 h)
keep image sha256:1d3e (1.2GB) (unused for only 48 h)
dockerclean.sh: dry run, 3 object(s) could be removed
The first lines (the disk usage and the mode) are the same as before and are left out. Volumes are not included because -v is missing.
Removing Objects
$ ./dockerclean.sh -y -v -o 48
...
Mode: REMOVE objects unused for 48 h or more
Stopped containers
removed container old-migration (python:3.12)
keep container test-db (postgres:16) (unused for only 5 h)
FAILED container stuck-job (alpine:3.20) (still in use?)
removed container never-started (nginx:1.27)
keep container build-tmp (node:22) (unused for only 30 h)
Dangling images
removed image sha256:9f1a (412MB)
keep image sha256:7c2b (88MB) (unused for only 3 h)
removed image sha256:1d3e (1.2GB)
Unused volumes (their data cannot be recovered)
removed volume pgdata_old
removed volume cache_tmp
dockerclean.sh: removed 6 object(s), 1 failed
...
$ echo $?
1
One removal failed, and the script went on with the other objects, because a single stubborn object should not stop the whole cleanup. The failure is counted and decides the exit status. Containers are processed before images on purpose: a dangling image that is still referenced by a stopped container cannot be removed, and it becomes removable once that container is gone.
Quiet Mode and Errors
$ ./dockerclean.sh -q -y
dockerclean.sh: could not remove container stuck-job (alpine:3.20)
dockerclean.sh: removed 5 object(s), 1 failed
(This run started from the original test data, with the default limit of 24 hours.) With -q only the summary and the errors are printed. The first line goes to standard error and the second to standard output.
When Docker Is Not Available
$ DOCKER_DOWN=1 ./dockerclean.sh
dockerclean.sh: cannot reach the Docker daemon (is it running? are you in the docker group?)
$ ./dockerclean.sh -o x
dockerclean.sh: -o needs a whole number of hours
$ ./dockerclean.sh -z
dockerclean.sh: unknown option -z (try -h)
The first command exits with status 3, the other two with status 2. The distinct codes let a calling script tell a missing daemon from a wrong option.
Using the Docker Built-in Commands
Docker has its own cleanup commands. Knowing them shows what the script adds:
docker container prune --filter "until=24h" # stopped containers older than 24 h
docker image prune # dangling images
docker volume prune # unused volumes (asks for confirmation)
docker builder prune --filter "until=168h" # build cache older than a week
docker system prune # containers, networks, dangling images, build cache
They are fast and well tested. What they do not do is list each object with its age before removing it, report each failure separately, or give you a script-friendly exit status per run. The script is a good fit for reviewable, logged cleanups; for a quick tidy-up of a development machine, the built-in commands are enough. The build cache (980 MB in the example above) is a common source of wasted space, and the script leaves it to docker builder prune.
Scheduling
This crontab line (lesson 170) removes stopped containers and dangling images that have been idle for a week, every Sunday at 03:15, and keeps a log. Volumes are not included, so no data can be lost:
15 3 * * 0 /usr/local/bin/dockerclean.sh -q -y -o 168 >> /var/log/dockerclean.log 2>&1
Run the same command without -y for the first week, look at what it reports (dockerclean.sh -o 168), and only then switch to the version with -y. On a CI server that builds images all day, run it every night with a shorter limit.
Ideas for Extending the Project
- Disk threshold. Run the cleanup only when the disk that holds
/var/lib/dockeris more than 80% full (lesson 166), so that a healthy server is left alone. - Protected names. Read a list of container name patterns from a file and never remove those, even when they are stopped.
- Image age by tag. Remove tagged images of an application, for example
myapp, except the newest five, usingdocker image ls --formatandsort. - Report in bytes. Parse the sizes from
docker image lswithnumfmt --from=iecand print how much space was freed. - Notification. Send the summary through the script from lesson 173 whenever a removal fails.