-
Notifications
You must be signed in to change notification settings - Fork 1
Docker Cleaner
doronshai edited this page Feb 16, 2017
·
3 revisions
#!/bin/bash
IMAGES_TO_KEEP=${1}
BRANCH_TYPE=${2}
DOCKER_GREP_TEXT=${3}
sudo docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Digest}}\t{{.CreatedAt}}\t{{.Size}}\t{{.ID}}"| grep -e $DOCKER_GREP_TEXT | uniq -f 6 > images.txt
TOTAL_IMAGES=`cat images.txt | wc -l`
echo "======= TOTAL_IMAGES ($BRANCH_TYPE) ========== $TOTAL_IMAGES"
echo "======= IMAGES_TO_KEEP ($BRANCH_TYPE) ======== $IMAGES_TO_KEEP"
if [ "$TOTAL_IMAGES" -gt "$IMAGES_TO_KEEP" ]; then
IMAGES_TO_REMOVE=`expr $TOTAL_IMAGES - $IMAGES_TO_KEEP`
echo "======= AMOUNT OF IMAGES EXCEED LIMIT ( $TOTAL_IMAGES > $IMAGES_TO_KEEP) ======="
echo "======= IMAGES_TO_REMOVE === $IMAGES_TO_REMOVE"
START_REMOVE_AT=`expr $TOTAL_IMAGES - $IMAGES_TO_REMOVE + 1`
echo "======= START_REMOVE_AT === $START_REMOVE_AT ======"
sed ''"$START_REMOVE_AT"','"$TOTAL_IMAGES"'!d' images.txt > images_to_delete.txt
echo "=============== REMOVING $IMAGES_TO_REMOVE IMAGES =============="
awk '{ print $1 }' images_to_delete.txt | xargs sudo docker rmi -f
if [ $(sudo docker images -q -f "dangling=true" | wc -l) -gt "0" ]; then
echo "=============== REMOVING DANGLING IMAGES =============="
sudo docker rmi $(sudo docker images -f "dangling=true" -q) # add a call to prune once we switch to docker 1.13
fi
else
echo "======= AMOUNT OF IMAGES ($BRANCH_TYPE) IS OK ( $TOTAL_IMAGES ) ======="
fi