To read more articles like this, visit my blog
The Problem
Whenever I am playing with docker, my local machine gets bloated with lots of images after several docker build
commands. The latest
one is tagged latest The previous versions become invalid but don't get deleted.
So when I run the command docker images
The list looks something like this with lots of invalid images…
Normal Solution
Normally the solution is to remove each image with something like
docker rmi -f IMAGE_ID
So now I have to remove each image one by one by their image id. Which is not fun at all.
Shortcut Solution
To delete all the invalid images (with the name/tag none
) one can simply run the following command. . .
docker images | grep none| tr -s ' ' | cut -d ' ' -f 3 | xargs -I {} docker rmi -f {}
Want to learn something more about those commands? Continue reading. . .
Explanation
We will talk about each of the commands that help us to achieve this. And learn some more about Linux on the way. . .
grep
- The first part of the command
docker images
simply lists all the images. The commandgrep none
filters the images having the word none inside them. So we can see all the invalid images with this command.
This is a simple use of the command grep. It is a very powerful command. We can add customized logic to remove docker images using this command!
tr
Next command is tr -s ' '
. It is a command that helps us to squeeze a string with our character of choice. We can see there are multiple spaces between the name, tag, image ID. So using this command we can minimize the space between them.
After running this command we can see the names are now evenly spaced.
cut
cut -d ' ' -f 3
This command helps us to cut a part of the input string. The option -d ' '
helps to set the separating delimiter as space. And -f 3
specifies that we want the 3rd part of the string.
If we run this command it will give us all the image id list with the tag none
xargs
The last part of the command is
xargs -I {} docker rmi -f {}
This command takes the output from a command and supplies it as input to another command. In our case, we want to use the IMAGE ID list as an input to docker rmi -f
.
After running the whole command you can see all your unwanted images are deleted now.
You can verify with the command docker images
again to verify that all the unwanted images are gone now.
You can play with the command if you want another kind of filtering with the first grep
command as it supports filtering with regular expressions too.
That’s it for today. Happy Coding! :D
*Get in touch with me via LinkedIn or my Personal Website. *
Top comments (0)