0
0
DockerHow-ToBeginner · 3 min read

How to Use Docker rmi to Remove Images Safely

Use the docker rmi command followed by the image ID or name to remove Docker images from your system. This helps free up space by deleting unused images safely.
📐

Syntax

The basic syntax of docker rmi is simple:

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

Here, IMAGE can be the image ID or the image name (with optional tag). You can specify multiple images separated by spaces.

Common options include:

  • -f or --force: Force removal of the image even if it is being used by stopped containers.
  • --no-prune: Do not delete untagged parent images.
bash
docker rmi [OPTIONS] IMAGE [IMAGE...]
💻

Example

This example shows how to remove a Docker image by its name and ID. First, list images, then remove one by name and one by ID.

bash
docker images
# Output shows images with REPOSITORY, TAG, IMAGE ID

docker rmi alpine:3.18
# Removes the image named alpine with tag 3.18

docker rmi 7f4a2142a0f9
# Removes the image by its IMAGE ID
Output
REPOSITORY TAG IMAGE ID CREATED SIZE alpine 3.18 7f4a2142a0f9 2 weeks ago 5.61MB Untagged: alpine:3.18 Deleted: sha256:7f4a2142a0f9... Deleted: sha256:abc123... Deleted: sha256:7f4a2142a0f9...
⚠️

Common Pitfalls

Common mistakes when using docker rmi include:

  • Trying to remove an image that is currently used by a running container, which will fail unless you use -f.
  • Confusing image names and tags; you must specify the correct tag or use :latest if no tag is given.
  • Not realizing that removing an image does not remove containers created from it.

Example of wrong and right usage:

bash
docker rmi alpine
# Fails if alpine:latest is used by a running container

docker rmi -f alpine
# Forces removal even if used by stopped containers
Output
Error response from daemon: conflict: unable to delete image (must be forced) - image is being used by running container Deleted: sha256:7f4a2142a0f9...
📊

Quick Reference

CommandDescription
docker rmi IMAGERemove one or more images by name or ID
docker rmi -f IMAGEForce remove image even if used by stopped containers
docker rmi --no-prune IMAGERemove image without deleting untagged parents
docker imagesList all images to find IMAGE IDs or names

Key Takeaways

Use docker rmi IMAGE to remove images by name or ID.
Add -f to force removal if images are used by stopped containers.
Always check running containers before removing images to avoid errors.
Removing an image does not delete containers created from it.
Use docker images to list images and find correct IDs or names.