-
-
Save eduardocardoso/82a629882ddb02ab3677 to your computer and use it in GitHub Desktop.
#!/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" |
It probably shows docker usage when running again because it tries to remove an empty set of containers and/or images. It's harmless but can be improved by adding a simple check
I improved the error handling and behavior when there is nothing to remove, now it runs cleanly under a cron manager like 'cronic': https://gist.github.com/stevenschlansker/51c319cdc7cd2764ce48
This script removes "Data Volume Containers" (https://docs.docker.com/userguide/dockervolumes) - they are picked up by that "status=exited" filter even though they were never started. Docker bug?
Anyhow, I amended the script to exclude containers named "*-data" in my fork: https://gist.github.com/graemian/fdf32edf1592d1cea944
I get errors, the script tried to remove images in use, the don't check if an image is in use before try to remove? Thank you.
Removing unused docker images
Error response from daemon: Conflict, cannot delete 91e54dfb1179 because the running container 4960a1706ac3 is using it, stop it and use -f to force
Error: failed to remove images: [ubuntu:14.04]
@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.
Thanks a lot!
I improve the image id list by manage none tag and use digest
https://gist.github.com/Dufgui/72debe81068bf3ecd7d8
removes 'all' images and outputs docker usage when running again
script ran while all containers where stopped, correct but surprising behavior.