Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Remove Untagged Docker Images From Your Docker Host Via The CLI

TwitterFacebookRedditLinkedInHacker News

If you’re like me, when it comes to Docker, you probably build images non-stop. I must admit that when I create images, I don’t create any special tags, even though I should. Instead every build uses the latest tag because that is enough to meet my needs. Regardless of what tags you use, you may find yourself building the same thing over and over. When this happens, the previous image remains on your machine, but becomes untagged to make room for the new build.

So how do you prevent having potentially hundreds of untagged Docker images lingering on your machine? We’re going to see how to quickly remove them.

Building custom Docker images should not be foreign to you at this point. If they are, you might check out a previous article I wrote titled, Build a Custom Docker Image for Your Containerized Web Application.

When listing your currently available images, you can actually filter the results. To filter the results for only untagged images, also referred to as dangling images, execute the following command:

docker images -f "dangling=true"

Alright, so that will let us list the untagged Docker images, but how about removing them? We can actually merge two commands together to accomplish this. Try executing the following command:

docker rmi $(docker images -f "dangling=true" -q)

We’re using the --quiet tag or -q for short because we only want the id value. The image results are removed at that point. While you can’t remove these images on build, you can always set up a nightly scheduled task or cron to execute the command for removing images.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.