DEV Community

Andrei Dascalu
Andrei Dascalu

Posted on

Docker cleanup: images by name search

There's nothing more annoying than collecting docker images locally and suddenly stateful application containers (like databases, mySQL, RabbitMQ) suddenly exiting because they don't have space left on the (usually VM) where they are running.

You can docker system prune -a to clean as much as possible or you can docker rmi everything, but what if you want to do a bit more targeted cleaning?

docker image ls will list all images with some info split in columns. First column is the image name, the second column contains the tag.

Now, we know that images share layers so deleting one won't necessarily free up all the space since some layers may still be linked to other images but we can improve cleanup by untagging images. How to do that in a more targeted way? By listing them and then joining the name column and the tag column and then passing it all to docker rmi. AWK comes to the rescue!

docker image ls | grep "MY SEARCH" | awk '{print $1 ":" $2}' | xargs docker rmi
Enter fullscreen mode Exit fullscreen mode

Of course, feel free to replace grep with your preferred search command as long as its output only filters docker image ls output and doesn't extract information from it, as AWK expects the columnised output.

Note: you should still do a

docker system prune
Enter fullscreen mode Exit fullscreen mode

afterwards as unlinking tags only frees up layers but those layers may remain stored locally - but docker prune will remove the dangling ones (eg: not tied to tagged images or to running containers).

Top comments (0)