Skip to content

Instantly share code, notes, and snippets.

@vkhatri
Created November 8, 2016 11:04
Show Gist options
  • Save vkhatri/85c48d50276d605eca190d032ba6c5cc to your computer and use it in GitHub Desktop.
Save vkhatri/85c48d50276d605eca190d032ba6c5cc to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
if [ -f "/usr/bin/docker" ]; then
exited=$(docker ps -a -q -f status=exited | wc -l)
if [ $exited == "0" ]; then
echo "No exited container to Remove"
else
echo "Removing exited docker containers..."
docker rm -v $(docker ps -a -q -f status=exited)
fi
dangl=$(docker images --no-trunc -q -f "dangling=true" | wc -l)
if [ $dangl == "0" ]; then
echo "No orphan image to Remove"
else
echo "Removing dangling images..."
docker rmi $(docker images --no-trunc -q -f "dangling=true")
fi
echo "Removing unused Volumes..."
docker run -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/docker:/var/lib/docker --rm martin/docker-cleanup-volumes
echo "Removing unused docker images"
images=($(docker images --digests | egrep -v 'martin/docker-cleanup-volumes' | 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[*]} "
running=$(docker ps | egrep -v 'shipimg/runsh|shipimg/mexec|CONTAINER ID'| wc -l)
if [ $running == "0" ]; then
if [ -z $remove_images ]; then
echo "No Ununsed Image to Remove"
else
echo "Running idle, Removing Unused Images..."
echo ${remove_images} | xargs -r docker rmi
fi
else
echo "Currently running $running non-base containers"
fi
else
echo Not a Docker.
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment