Remove Docker image and container with a criteria (Tech Tip #60)

You have installed multiple Docker images and would like to clean them up using rmi command. So, you list all the images as:

Then try to remove the “arungupta/wildfly-centos” image as shown below, but get an error:

So you follow the recommendation of using -f switch but get another error:

What do you do ?

This message indicates that the image is used by one of the containers and that’s why could not be removed. The error message is very ambiguous and a #9458 has been filed for the same.

In the meanwhile, an easy way to solve this is to list all the containers as shown:

There are lots of containers that are using “arungupta/wildfly-centos” image but none of them seem to be running. If there are any containers that are running then you need to stop them as:

Remove the containers that are using this image as:

The criteria here is specified as a grep pattern.

docker ps command has other options to specify criteria as well such as only the latest created containers or containers in a particular status. For example, containers that exited with status -1 can be seen as:

All running containers, as opposed to meeting a specific criteria, can be removed as:

And now the image can be easily removed as

Just like removing all containers, all images can be removed as:

Enjoy!

Be Sociable, Share!
  • Tweet

One thought on “Remove Docker image and container with a criteria (Tech Tip #60)

  1. Hi Arun,

    I used your commands and faced some problems. All the data containers I used got removed as well. I was shocked because the backup is at the moment not accessible. But thanks you did not remove the containers with -v … so the data stayed on the server in the folder /var/lib/docker/vfs/dir//

    Would be great if you could include this into your post.

    Best,
    Patrick

Leave a Reply

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


− 6 = two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">