Improved docker image pruning

This commit is contained in:
DerLinkman 2023-10-19 12:31:13 +02:00
parent 61e23b6b81
commit 6c6fde8e2e

View File

@ -32,47 +32,40 @@ prefetch_images() {
} }
docker_garbage() { docker_garbage() {
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
IMGS_TO_DELETE=() IMGS_TO_DELETE=()
for container in $(grep -oP "image: \Kmailcow.+" "${SCRIPT_DIR}/docker-compose.yml"); do
REPOSITORY=${container/:*}
TAG=${container/*:}
V_MAIN=${container/*.}
V_SUB=${container/*.}
EXISTING_TAGS=$(docker images | grep ${REPOSITORY} | awk '{ print $2 }')
for existing_tag in ${EXISTING_TAGS[@]}; do
V_MAIN_EXISTING=${existing_tag/*.}
V_SUB_EXISTING=${existing_tag/*.}
# Not an integer
[[ ! $V_MAIN_EXISTING =~ ^[0-9]+$ ]] && continue
[[ ! $V_SUB_EXISTING =~ ^[0-9]+$ ]] && continue
if [[ $V_MAIN_EXISTING == "latest" ]]; then declare -A IMAGES_INFO
echo "Found deprecated label \"latest\" for repository $REPOSITORY, it should be deleted." COMPOSE_IMAGES=($(grep -oP "image: \Kmailcow.+" "${SCRIPT_DIR}/docker-compose.yml"))
IMGS_TO_DELETE+=($REPOSITORY:$existing_tag)
elif [[ $V_MAIN_EXISTING -lt $V_MAIN ]]; then for existing_image in $(docker images --format "{{.ID}}:{{.Repository}}:{{.Tag}}" | grep 'mailcow/'); do
echo "Found tag $existing_tag for $REPOSITORY, which is older than the current tag $TAG and should be deleted." ID=$(echo $existing_image | cut -d ':' -f 1)
IMGS_TO_DELETE+=($REPOSITORY:$existing_tag) REPOSITORY=$(echo $existing_image | cut -d ':' -f 2)
elif [[ $V_SUB_EXISTING -lt $V_SUB ]]; then TAG=$(echo $existing_image | cut -d ':' -f 3)
echo "Found tag $existing_tag for $REPOSITORY, which is older than the current tag $TAG and should be deleted."
IMGS_TO_DELETE+=($REPOSITORY:$existing_tag) if [[ " ${COMPOSE_IMAGES[@]} " =~ " ${REPOSITORY}:${TAG} " ]]; then
continue
else
IMGS_TO_DELETE+=("$ID")
IMAGES_INFO["$ID"]="$REPOSITORY:$TAG"
fi fi
done done
done
if [[ ! -z ${IMGS_TO_DELETE[*]} ]]; then if [[ ! -z ${IMGS_TO_DELETE[*]} ]]; then
echo "Run the following command to delete unused image tags:" echo "The following unused mailcow images were found:"
echo for id in "${IMGS_TO_DELETE[@]}"; do
echo " docker rmi ${IMGS_TO_DELETE[*]}" echo " ${IMAGES_INFO[$id]} ($id)"
echo done
if [ ! $FORCE ]; then if [ ! $FORCE ]; then
read -r -p "Do you want to delete old image tags right now? [y/N] " response read -r -p "Do you want to delete them to free up some space? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]; then if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
docker rmi ${IMGS_TO_DELETE[*]} docker rmi ${IMGS_TO_DELETE[*]}
else else
echo "OK, skipped." echo "OK, skipped."
fi fi
else else
echo "Running image removal without extra confirmation due to force mode." echo "Running in forced mode! Force removing old mailcow images..."
docker rmi ${IMGS_TO_DELETE[*]} docker rmi ${IMGS_TO_DELETE[*]}
fi fi
echo -e "\e[32mFurther cleanup...\e[0m" echo -e "\e[32mFurther cleanup...\e[0m"