Cleanup Docker Images and Exited Containers

It’s pretty easy to accumulate Docker containers and images on a development machine. Normally, every container that is ran is preserved on your machine. Try running docker ps -a and see how much you’ve accumulated over time.

Concerned about loss of disk space over time, I found a blog post that talked about cleaning up after Docker. Part of the article talked about removing dangling images, or intermediary images that are created while building other containers.

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

However, I also wanted to clean up exited containers that accumulate from running docker-compose run commands, but leave the containers that are automatically started and stopped from running docker-compose up.

I ended up with the following bash alias to help me retrieve previous disk space:

alias docker-cleanup='docker rm $(docker ps -a -f "name=_run_" -q) && docker rmi $(docker images -f "dangling=true" -q)'

As a bonus, here’s the bash alias I use to quickly connect a terminal session to the default docker-machine.

alias docker-setup='docker-machine start default; eval "$(/usr/local/bin/docker-machine env default)"'