Docker Container Cleanup – Code to Make it Easy

Short Cuts for Cleaning up Your Docker Container.

Cleaning up your docker container can be useful. I need to cleanup my Docker container frequently as part of developing and testing the code that is running inside. I got tired of doing cut and paste of container and image ids. So I created a couple of shortcuts.

First I created bash aliases to save some typing.

alias dcrun="docker ps -a -q --filter="status=running"" alias dcall="docker ps -a -q"

dcrun will print out the running container ids in a single column list
dcall will print out all of the container ids in a single column list

I am a bit old fashion and hate typing dollar signs and parentheses so I use the xargs program instead.
xargs will work with any program. It basically takes all of the input that is being piped in and adds it as parameters to the end of the command that you are running.

To stop all running containers:

dcrun | xargs docker stop

To remove all containers:

dcall | xargs docker rm

The other way with dollar signs and parentheses:

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

Some tips on handling images from multiple repositories and nuances of the docker run command

Leave a Reply