Docker learned to find unused images itself ❤️

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2018-07-08 21:41:10 +02:00
parent 6924335526
commit 885a8c553d
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E

View file

@ -11,20 +11,5 @@ step "Removing containers created / exited >= ~1h ago..."
CONTAINERS=$(docker ps -a | gawk '/(hours?|days?|weeks?|months?) ago\s+(Created|Exited)/{ print $1 }' | xargs)
[ -n "${CONTAINERS}" ] && docker rm ${CONTAINERS}
step "Untagging all images not used by containers..."
PS_OUTPUT=$(docker ps -a)
for img in $(docker images | gawk '/^[a-z].*(hours?|days?|weeks?|months?) ago/{ print $1":"$2 }' | grep -v '<none>' | sort | uniq); do
imghash=$(docker inspect "${img}" | jq -r '.[0].Id' | sed -E 's/^sha256:(.{12}).*/\1/')
# Check if image is currently active
(echo "${PS_OUTPUT}" | grep -q "\s${img}\s") && continue
# Check if image with stripped ":latest" is currently active
(echo "${PS_OUTPUT}" | grep -q "\s${img%:latest}\s") && continue
# Check if image hash is currently active (sometimes docker looses named references)
(echo "${PS_OUTPUT}" | grep -q "\s${imghash}\s") && continue
docker rmi --no-prune "${img}"
done
step "Removing dangling images..."
docker image prune -f
step "Removing unused and dangling images..."
docker image prune -a -f