Last active
April 3, 2023 08:23
-
-
Save eduardocardoso/82a629882ddb02ab3677 to your computer and use it in GitHub Desktop.
Script to delete exited containers and untagged/unused images from docker
This file contains hidden or 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 | |
echo "Removing dangling images..." | |
docker images --no-trunc -q -f dangling=true | xargs -r docker rmi | |
echo "Removing unused docker images" | |
images=($(docker images --digests | tail -n +2 | awk '{ img_id=$1; if($2!="<none>")img_id=img_id":"$2; if($3!="<none>") img_id=img_id"@"$3; print img_id}')) | |
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" |
Thanks a lot!
I improve the image id list by manage none tag and use digest
https://gist.github.com/Dufgui/72debe81068bf3ecd7d8
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@rafaelcapucho It is probably because the container was started without providing a tag, the check that this script does is simply concatenating all images with tags and removing the ones that are not shown by docker ps.
So if there is a container running the latest tag of an image without specifying its tag this script will not detect it as running and will try to remove the image.