Docker: purge exited containers and remove old images


Scenario

You have been using Docker for a while--downloading various Docker images and spinning containers up and down. Your list of "Exited" containers has grown and your file system space is dwindling because of all those Docker images.

Purge, Baby, Purge

To remove all "Exited" containers, use the following command:

# docker ps -a | grep 'Exited' | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm

To remove all Docker images that are not tagged as "latest" (notice the invert-match grep option, -v), run this:

# docker images | grep -v 'latest' | awk '{print $3}' | xargs --no-run-if-empty sudo docker rmi

And to get them both in one swoop...

# docker rm $(docker ps --no-trunc -aq); docker rmi $(docker images --filter "dangling=true")

Keep it lean and mean. Edit crontab.

# crontab -e

Add this to purge containers and images every morning at 2:00 am.

0 2 * * * docker rm $(docker ps --no-trunc -aq) > /dev/null 2>&1; docker rmi $(docker images --filter "dangling=true") > /dev/null 2>&1