-
-
Save jbq/ad0ff47480d03e24e4d2f49d68f7fb93 to your computer and use it in GitHub Desktop.
Script to delete exited containers and untagged/unused images from docker
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 -o errexit | |
echo "Removing exited docker containers..." | |
docker ps -a -f status=exited -q | xargs -r docker rm -v | |
# Do not remove dangling images they may still be in use | |
#echo "Removing dangling images..." | |
#docker images --no-trunc -q -f dangling=true | xargs -r docker rmi | |
echo "Removing dangling volumes..." | |
docker volume ls -qf dangling=true | xargs -r docker volume rm | |
echo "Removing unused docker images..." | |
images=($(docker images --digests | tail -n +2 | awk '{ | |
if ($1!="<none>") { | |
img_id=$1; | |
if($2!="<none>") | |
img_id=img_id":"$2; | |
if($3!="<none>") | |
img_id=img_id"@"$3; | |
} else { | |
img_id=$4; | |
} | |
print img_id}' | sed -e 's/:latest//')) | |
containers=($(docker ps -a | tail -n +2 | awk '{print $2}')) | |
containers_reg=" ${containers[*]} " | |
remove=() | |
for item in ${images[@]}; do | |
if [[ ! $containers_reg =~ " $item " ]]; then | |
remove+=($item) | |
fi | |
done | |
remove_images=" ${remove[*]} " | |
echo ${remove_images} | xargs -r docker rmi | |
echo "Done" |
Updated:
- Do not remove dangling images they may still be in use
- Fix for dangling images (the ones that appear as
<none>
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated fork to avoid removing images tagged
latest
and still used by containers