Docker. You know that I love it. I guess maybe sometimes I love it a little too much because on some of my test servers I have been filling up a lot of GB with new images and containers. All of which hang around indefinitely if you don’t clear them. Add to that if you have a continuous integration pipeline that builds a new container every time you do a commit/push and you have an ever growing disk of redundant Docker containers and images.

Tidy Up Your Containers

A tidy server is a tidy mind?! Get rid of containers that you don’t want. Just don’t forget, if you get rid of them, you can’t get them back, so make sure you don’t have any persistant data (data you want to keep) in them. This will loop through all of your containers and find the ones that are exit-ed and kill them!

docker rm -v $(docker ps -a -q -f status=exited)

Tidy Up Your Images

Images can be as deadly to disk space as containers (I’m looking at things not using Alpine). So loop through all of your images and remove the dangling ones, generally ones that have been superseded by newer images:

docker rmi $(docker images -f "dangling=true" -q)

Set it in a cron job

And because we don’t want to have to manually do this all of the time, set it on a cron job. I normally think every 4 hours (42 */4 * * *) is ok if it is a small team, but you might want every hour if you are a bigger team (42 * * * *).

42 */4 * * * docker rmi $(docker images -f "dangling=true" -q)
42 */4 * * * docker rm -v $(docker ps -a -q -f status=exited)