Docker: Keep it clean!

Clean up your docker containers.

Posted by Cloudscombined on September 26, 2017

After starting and stop all of those containers, files get left behind (so you might inspect it later if you desire). But, if you are running out of disk space, and Docker may be contributing to that, then give this script a try.

This script uses jq, install it if needed.

           
sudo apt-get install -y jq 

Create a script called cleanup-docker.sh, and paste the contents below. Don't forget to chmod +x cleanup-docker.sh so the script will run.


#!/bin/bash
# hosted at https://gitlab.com/shallawell/clean-up-docker/raw/master/cleanup-docker.sh
        
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

echo " current disk space"
df -h

# remove exited containers:
docker ps --filter status=dead --filter status=exited -aq | xargs -r docker rm -v

# remove unused images:
docker images --no-trunc | grep '' | awk '{ print $3 }' | xargs -r docker rmi

# remove unused volumes:
find '/var/lib/docker/volumes/' -mindepth 1 -maxdepth 1 -type d | grep -vFf <(
  docker ps -aq | xargs docker inspect | jq -r '.[] | .Mounts | .[] | .Name | select(.)'
) | xargs -r rm -fr

echo "new disk space"
df -h



Then just execute it with ./cleanup-docker.sh

This should allow you to reclaim some disk space -- maybe.

If you have any questions, contact me via links below