DEV Community

Andrei Dascalu
Andrei Dascalu

Posted on

3 2

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).

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay