Skip to content

Instantly share code, notes, and snippets.

Last active May 2, 2019 20:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
set -e
sort_func () {
tr ' ' '\n' | sort -u | (grep -v '^$' || true)
cutoff=$(date -Is --date='10 days ago')
# Get list of images used recently
# NOTE: events store image names, not IDs.
# NOTE: events may reference images which no longer exist.
used_image_names=$(docker events --since "$cutoff" --until="$(date -Is)" --format '{{.From}}' | sort_func)
echo Recently used image names: "$(wc -w <<<"$used_image_names")"
used_image_ids=$( (xargs -r -n1 docker image inspect --format='{{.ID}}' <<<"$used_image_names" 2>/dev/null || true) | sort_func)
echo Recently used image ids: "$(wc -w <<<"$used_image_ids")"
# Get list of images with old CreatedAt dates
for image_id in $(docker image ls -q); do
if [ "$(docker inspect --format='{{.Created}}' --type=image "$image_id")" \< "$cutoff" ]; then
old_image_ids+=" $(docker image inspect "$image_id" --format='{{.ID}}')"
old_image_ids=$(sort_func <<<"$old_image_ids")
echo Old image IDs: "$(wc -w <<<"$old_image_ids")"
# Remove old images which have not been recently used
to_remove=$(comm -23 <( echo "$old_image_ids" ) <( echo "$used_image_ids" ) )
echo Image IDs to remove: "$(wc -w <<<"$to_remove")"
for image_id in $to_remove; do
# NOTE: `docker rmi image_id` doesn't work if the image has multiple tags.
# NOTE: `docker rmi --force` is not safe if there is a running container.
for image_name in $(docker inspect "$image_id" --format='{{join .RepoTags " "}}') "$image_id"; do
docker image rm "$image_name" || true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment