Skip to content

Cleaning Up Docker

If you extensively use Docker on your machine, you might have noticed how unused instances take up a lot of space on your hard drive. Especially if you do not use the --rm flag with docker run, you will soon collect a big number of stopped Docker containers.

I manually start this script when I feel like cleaning up some space. Feel free to copy it and use it in your .bashrc file:

    sudo docker rm -v $(sudo docker ps --filter status=exited -q 2>/dev/null) 2>
    sudo docker rmi $(sudo docker images --filter dangling=true -q 2>/dev/null) 

Depending on your machine, you might need to remove the sudo commands. I added it because in my setup I do not use the docker group used in the documentation. Doing this is a huge security issue and I do not recommend using docker without sudo commands (more details below).

So once you load this new function into your bash session, you can use docker_cleanup to start the process. If there are any containers, the script will output the container hashes that it deleted. The script also looks for unused and intermediate images to delete. This is usually safe to remove, so the script won’t remove anything that is actually used somewhere. Here is an example output after running a few containers:

$ docker_cleanup 

If you have any questions or remarks about this script, please leave a comment below.

Security risks of the docker group

If you are wondering what can happen if you add your current user to the docker group as explained in the official documentation, imagine an attacker that executes the following line in your terminal:

docker run -v /:/mnt --rm -it alpine chroot /mnt sh

For my setup, this asks for the sudo password, while on a system with the docker group setup, this allows anyone to get root privileges on your host file system without prompt. From there, you can easily add new (root) users to the system or extend your privileges. You can check this blog post for more information.

Title Photo by No Revisions on Unsplash

Published inTechnologyTips and Tricks

Be First to Comment

Leave a Reply

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