Remove an image by ID using force
In this step, we will learn how to remove a Docker image using its Image ID, and specifically, how to use the force option (-f
or --force
) when necessary. Removing by ID is useful when you want to be precise about which image you are removing, especially if multiple tags point to the same image.
First, let's pull an image that we can then remove by ID. We'll use the ubuntu
image. If you already have it, the pull will be quick.
docker pull ubuntu
Now, list the images to get the Image ID of the ubuntu
image.
docker images
Find the ubuntu
image in the output and note its IMAGE ID
. It will be a long string of hexadecimal characters. You only need the first few characters (usually 3 or more) to uniquely identify the image.
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest 270000000000 2 weeks ago 77.8MB
Let's try to remove the image using its ID without the force option first. Replace YOUR_IMAGE_ID
with the actual Image ID you noted from the docker images
output.
docker rmi YOUR_IMAGE_ID
If the image is not being used by any running or stopped containers, this command will likely succeed and remove the image. However, if there is a container based on this image, you will get an error message indicating that the image is being used by a container and cannot be removed.
To demonstrate the use of the force option, let's first run a container based on the ubuntu
image.
docker run -d ubuntu sleep 3600
This command runs an Ubuntu container in detached mode (-d
) and keeps it running for an hour (sleep 3600
).
Now, try to remove the ubuntu
image by its ID again without the force option.
docker rmi YOUR_IMAGE_ID
You should receive an error message similar to this:
Error response from daemon: conflict: unable to remove repository reference "ubuntu:latest" (must force) - image is referenced by one or more containers: 000000000000 (created ...)
This error occurs because a container is using the image. To remove an image that is being used by a container, you need to use the force option (-f
).
Now, let's remove the image using its ID with the force option. Replace YOUR_IMAGE_ID
with the actual Image ID.
docker rmi -f YOUR_IMAGE_ID
The force option tells Docker to remove the image even if it is being used by a container. Docker will first stop and remove any containers that are using the image, and then remove the image itself. The output will show that the image and its layers are deleted.
Untagged: ubuntu:latest
Deleted: sha256:2700000000000000000000000000000000000000000000000000000000000000
Deleted: sha256:0000000000000000000000000000000000000000000000000000000000000000
... (more Deleted lines)
List the images again to confirm that the ubuntu
image is gone.
docker images
The ubuntu
image should no longer be in the list.
Using the force option should be done with caution, as it will stop and remove containers without further confirmation.