Skip to content

Instantly share code, notes, and snippets.

@mnuessler
Last active August 29, 2015 14:25
Show Gist options
  • Save mnuessler/dce5d1e57e48eb345853 to your computer and use it in GitHub Desktop.
Save mnuessler/dce5d1e57e48eb345853 to your computer and use it in GitHub Desktop.
Yet another docker cleanup script. Deletes stopped docker containers and untagged images, prints information about freed disk space.
#!/bin/bash
#
# Cleans up docker files:
# - Deletes untagged docker images
# - Deletes stopped docker containers
# - Deletes long-running docker containers (use with care!)
set -e
if [ $# -eq 0 ]; then
echo "Usage: $0 --stopped --long-running --untagged"
exit 1
fi
output=echo
#output="logger -t docker-cleanup"
function delete_stopped_containers() {
local containers=$(docker ps -q -f status=exited)
if [ -n "$containers" ]; then
local count=$(echo $containers | wc -w)
$output "Deleting $count stopped docker containers"
docker rm $containers &> /dev/null
$output "Deleted $count stopped docker containers"
else
$output "No stopped docker containers found"
fi
}
function delete_untagged_images() {
local images=$(docker images -q -f dangling=true)
if [ -n "$images" ]; then
local count=$(echo $images | wc -w)
$output "Deleting $count untagged docker images"
docker rmi $images &> /dev/null
$output "Deleted $count untagged docker images"
else
$output "No untagged docker images found"
fi
}
function delete_long_running_containers() {
local containers=$(docker ps | grep -E 'Up (([3-9] hours)|([1-9][0-9]* (hours|days|weeks)))' | awk '{print $1}')
if [ -n "$containers" ]; then
local count=$(echo $containers | wc -w)
$output "Deleting $count long-running docker containers"
docker rm -f $containers &> /dev/null
else
$output "No long-running docker containers found"
fi
}
for arg in "$@"; do
case $arg in
--stopped)
delete_stopped_containers
;;
--long-running)
delete_long_running_containers
;;
--untagged)
delete_untagged_images
;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment