Last active
May 2, 2019 20:05
-
-
Save lukeyeager/4086dcce6cef90b4bed47d681b370628 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
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 | |
old_image_ids='' | |
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}}')" | |
fi | |
done | |
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 | |
done | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment