Cleanup Docker to free up memory

Posted by Harald Nezbeda on Mon 12 February 2018

It’s over a year since I decided moving to Docker and replace Vagrant. I’m now fully running on Docker for developing Python and PHP web applications, and had no worth to be considered issues until the last week when I ran out of memory on my HDD.

The problem started because I had only about 10GB of memory left and could not rebuild a Image for my Docker Compose setup. The process was just starting and eating up memory without outputting anything to the console. So my first thought was to find some ways to free up memory by deleting some files, but I quickly found out that there isn’t that much on my system that I can delete, and the memory must be used by something else.

I knew that images and containers can take a lots of space, so I started by removing those that I’m not using anymore, but doing this manually consumes lot’s of time. After some research I saw that newer versions of Docker already implemented commands that are used for this task. So I removed all unused images and container and made about 6GB more available. The same docs also provided command for removing networks and volumes. With networks I also had a problem in the past, so this command is pretty handy, even if it does not free up that much memory. What surprized me where the volumes, after I removed those I got an extra of 80GB of memory. I never realized how much space Docker is allocating to them.

Docker cleanup commands

# Remove all stopped containers
docker container prune

# Remove all unused volumes
docker volume prune

# Remove unused images
docker image prune

# Remove unused network
docker network prune

­# Remove all unused containers, volumes, images (in this order)
docker system prune

By aplying the -a option on each of the commands you can also remove the used instances, which is handy when deciding to cleanup everything.

Here are some more docker system commands that you can consider:

docker system df – Will show you how many images, containers and local volumes exist on the system, how many of them are used and the amount of memory that could be recovered if the prune command is used (without the -a option).

docker system info – A more detailed list of information regarding docker and your system