Skip to content

Instantly share code, notes, and snippets.

@kyeah
Created November 2, 2020 18:37
Show Gist options
  • Save kyeah/173dfb78a8d4952a0d14b41ee4d4c30c to your computer and use it in GitHub Desktop.
Save kyeah/173dfb78a8d4952a0d14b41ee4d4c30c to your computer and use it in GitHub Desktop.
Cleanup Docker
#!/usr/bin/env sh
# Script for cleaning up stopped containers and old/dangling images.
set -e
while getopts "f" opt; do
case "$opt" in
f) force=true
;;
*)
echo "unknown flag: $opt"
;;
esac
done
echo "Cleaning up stopped containers..."
containers=$(docker ps --filter status=created --filter status=exited -q 2>/dev/null)
echo $containers | xargs -n1 -I {} docker rm -v {} || true
echo "Cleaning up dangling images..."
dangling_images=$(docker images --filter dangling=true -q 2>/dev/null)
echo $dangling_images | xargs -n1 -I {} docker rmi {} || true
echo "Cleaning up images older than 10 days..."
images=$(docker images | grep ' ([1-9][0-9] days)\|weeks\|months' | awk '{ print $3 }' | awk '!seen[$0]++')
if [ "$force" = true ]; then
cmd='docker rmi -f $0 || true'
else
cmd='docker rmi $0 || true'
fi
echo $images | xargs -n1 sh -c "$cmd"
echo "Finished docker cleanup."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment