Skip to content

Instantly share code, notes, and snippets.

@rverst
Last active August 27, 2021 09:50
Show Gist options
  • Save rverst/e61b93419cc2276e67dc8d31d4b2d483 to your computer and use it in GitHub Desktop.
Save rverst/e61b93419cc2276e67dc8d31d4b2d483 to your computer and use it in GitHub Desktop.
Clean up unused docker volumes, images and containers
#!/usr/bin/env sh
is_root () { [ "$(id -u)" -eq 0 ]; }
is_docker_grp() { [ -n "$(id -Gn | grep docker)" ]; }
if ! is_root && ! is_docker_grp; then
echo "You need to be 'root' or in the 'docker'-group!"
echo "Try 'sudo docker_cleanup.sh'"
exit 1
fi
# Remove exited containers
docker ps -a -q -f status=exited | xargs --no-run-if-empty docker rm -v
# Remove dangling images
docker images -f "dangling=true" -q | xargs --no-run-if-empty docker rmi
# Remove unused images (2 month up)
docker images | awk '/months ago/ { print $3}' | xargs --no-run-if-empty docker rmi
# Remove unused images (2 years up)
docker images | awk '/years ago/ { print $3}' | xargs --no-run-if-empty docker rmi
# Remove dangling volumes
docker volume ls -qf dangling=true | xargs --no-run-if-empty docker volume rm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment