How to keep clean your Docker?

I’ve been playing around with Docker, perfect platform for developers and sysadmins to build, ship, and run distributed applications. It is cool – there is lot of possibilities how to use it to get my things done.

After playing with Docker, I’ve realized that my disk is running out of all my hard drive space so I started to investigate where my gigabytes went. Docker uses for running containers lot of images which could have about 1 gigabyte. And I had there a lot of images and most of them were stopped, untagged and useless.

But removing then manually takes some time and it is boring. Additionally Docker does not have any built-in commands for cleaning stopped containers and untagged images, so I put together some of command to do it my way.

Remove all untagged images

I had bunch of images that were not tagged. You can remove all untagged images using this command:
docker images | grep "^<none>" | awk -F$' ' '{print $3}'
This works by using rmi (docker command deleting docker image) with a list of image ids. To get the image ids we call docker images then pipe it to grep "^<none>". The grep will filter it down to only lines with the value ”<none>” in the repository column. Then to extract the id out of the third column we pipe it to awk '{print $3}' which will print the third column of each line passed to it.

Remove all stopped containers

To do it, you can simply execute this command:

docker rm $(docker ps -a -q)

This will remove all stopped containers by getting a list of all containers with docker ps -a -q and passing their ids to docker rm. This should not remove any running containers, and it will tell you it can’t remove a running image.

Leave a Reply

Your email address will not be published. Required fields are marked *