Keeping the whale happy: How to clean up after Docker
Once you’ve worked with Docker for a while, you have probably noticed that it eats disk space like a whale. And when that disk space runs out, everything on your server usually grinds to a halt.
Here are my top tips for tidying up after Docker, and keeping it running happily ever after.
The commands assume you are running Linux or Mac OS X with Docker 1.9 or newer; confirm with docker version.
Assess the situation
See disk space usage
df -h
See list of running containers
docker ps
See list of stored images
docker images
Generally safe cleanup commands
Delete orphaned and dangling volumes
docker volume rm $(docker volume ls -qf dangling=true)
Dangling volumes are volumes that are not being used by a container. Dangling images are images that are not referenced to by containers or other images.
Delete dangling and untagged images
docker rmi $(docker images -q -f dangling=true)
Cleanup commands, if you know what you’re doing OR like living on the edge
Delete exited containers
docker rm $(docker ps -aqf status=exited)
Note that this also deletes data containers you might have created.
Delete all images
docker rmi $(docker images -q)
Kill all running containers
docker kill $(docker ps -q)
Delete all containers
docker rm $(docker ps -aq)
The ‘official’ Docker cleanup method (as of Docker 1.13)
DELETE STOPPED CONTAINERS, AND VOLUMES AND NETWORKS THAT ARE NOT USED BY CONTAINERS
Delete stopped containers, and volumes and networks that are not used by containers
docker system prune -a
Note that this will also delete any data-only containers you might have created.
Tip: Get permission denied when running docker commands? If you get an error like this when running docker commands:
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
and you can work around it by running ‘sudo docker’, your user might not be in the docker group. You should avoid running sudo whenever possible, as it runs (possibly unsafe) programs with superuser privileges. Try running the following:
sudo usermod -aG docker $USER
After you log out and log back in, you should be able to run docker commands as your own user (ie. without ‘sudo’).
Pro tip: Clean dangling images and volumes weekly
Create a script with the following contents, save it as ~/docker-cleanup.sh
(you know how to use vim, right?):
#!/bin/bash
docker rmi $(docker images -q -f dangling=true)
docker volume rm $(docker volume ls -qf dangling=true)
Remember to make it executable with chmod 755 ~/docker-cleanup.sh
.
Add the following line to your crontab (run crontab -e
):
15 0 * * 1 ~/docker-cleanup.sh > /dev/null 2>&1
Ta-da! Your dangling images and volumes are cleaned automatically every Monday at quarter past midnight.
Releaseworks Academy has a free online training course on Docker & Jenkins best practices: https://www.releaseworksacademy.com/courses/best-practices-docker-jenkins