Remove images from Docker Images

You can remove an image using its short or long ID, its tag, or its digest in the Docker. For this we have to use the command:

docker rmi [OPTIONS] IMAGE [IMAGE...]

Where Options are:
-f, –force Force removal of the image
–help Print usage
–no-prune Do not delete untagged parents

Let’s see how this works. You cannot delete an image if it has been used to spawn containers or child images based on it. You would likely see an error message which resembles following:

Error response from daemon: conflict: unable to remove repository reference “mogo/ubuntu:telnet” (must force) – container 4888c45aa31c is using its referenced image a955c52ec9ec

Or

Error: Conflict, cannot delete image fd484f19954f because it is tagged in multiple repositories, use -f to force

Let’s see how this works. First we can identify images on our machine using below command:

docker images
List docker images on the machine
List docker images on the machine

Then lets’ say we want to delete image mogo/ubuntu:telnet. If we issue docker rmi command, we would see an error message like this:

docker rmi mogo/ubuntu:telnet
Error while removing images
Error while removing images

We can clearly see that one of the containers is dependent on it. We can verify by running below command to show container history:

docker ps -a
Referenced container in the image deletion command
Referenced container in the image deletion command

We have highlighted container in the reference. So, let’s first remove this container by using below command:

docker rm <container tag/id>
Remove the referenced container
Remove the referenced container

Once all the dependent containers are removed, we can safely delete image by running command

docker rmi <image tag/id/digest>
Output for image removal command
Output for image removal command

We should always remove dependent containers first although we can forcefully remove image by using -f. As you can see in below output, we forcefully removed image 5f43f6428531 which was referenced by container fa8ce5a92ac4. So when used -f, it removed only image leaving container with no parents:

containers still lingering if image is removed forcefully
containers still lingering if image is removed forcefully

Again, we can remove these containers later. However you should be removing image by removing all referenced images and containers first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s