Baeldung Pro – Ops – NPI EA (cat = Baeldung on Ops)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

Partner – Orkes – NPI EA (cat=Kubernetes)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Introduction

When using Docker, it’s critical to differentiate between Docker images and Docker containers. In short, an image is like a class, while containers are like objects in object-oriented programming.

In this tutorial, we’ll focus on the various ways of removing Docker images.

2. Why Remove Docker Images?

Managing Docker images is crucial for a smooth and efficient Docker experience. Over time, unused images can pile up, taking up valuable storage space. This might not only slow down the system but can also prevent new containers from running if we run out of free space.

As a result, removing outdated or unnecessary images regularly is like spring cleaning for a Docker environment. It keeps things tidy and ensures that the Docker Engine runs smoothly.

Moreover, removing unnecessary images helps us stay organized and focused on the images that actually matter for given projects.

3. Removing a Single Image

To begin with, we can easily remove a single Docker image using the docker rmi command.

First, we usually identify the image we want to delete. To do so, we run a command to list all images:

$ docker images

Once we find the image ID or name, we use the docker rmi command to remove it:

$ docker rmi <image_id>

However, if a container is still using the image, Docker prevents that image from being deleted. In this case, we first stop the container using docker stop:

$ docker stop <container_id>

Then, we remove the container with docker rm:

$ docker rm <container_id>

Notably, docker rmi and docker image rm are aliases. Hence, they work the same way: we can use either of them for this task.

4. Removing Multiple Images

Sometimes, we need to remove more than just one image. Let’s explore how to efficiently remove multiple Docker images at once, whether we want to target specific ones or clean up the entire system.

4.1. Basic Removal of Multiple Images

If there are a handful of images to remove, we can delete them all at once instead of running separate commands for each. After listing the images with docker images, we can pass their IDs to the docker rmi command.

For example, to remove three images with the IDs 1a2b3c4d, 5e6f7g8h, and 9i0j1k2l, we would run the rmi subcommand with several arguments:

$ docker rmi 1a2b3c4d 5e6f7g8h 9i0j1k2l

Thus, we delete all the images we specify in one go and free up valuable disk space. However, it’s a good practice to always double-check the image IDs before hitting enter, so we don’t delete something important.

4.2. Removing All Images

There are times when we might want to do a complete image cleanup and remove all Docker images from the system. This can be useful when starting a new project or simply to get a fresh slate.

Thankfully, there’s a command that gets the job done in one step. We can use a combination of the docker images and docker rmi commands along common shell syntax.

First, docker images -q lists all image IDs in a quiet format (only the IDs, no other details). Then, we feed those IDs into docker rmi using command substitution:

$ docker rmi $(docker images -q)

This command attempts to remove all images on the system. However, the command fails if containers are using any of those images.

In such cases, we must stop and remove those containers before retrying the image removal. Of course, it’s critical to proceed with caution, as this action is irreversible.

4.3. Removing Images Based on a Pattern

In addition to removing individual or all images, we might also want to target a specific group of images that share a common pattern in their names or tags. This is especially useful when we want to clean up images related to a specific project or version.

We can combine Docker commands with basic shell utilities like grep and awk to produce a filter that only retrieves some images. First, we list all images and then apply specific patterns of interest:

$ docker images | grep '<pattern>'

For example, let’s suppose we want to remove all images related to the project myapp:

$ docker images | grep 'myapp'

We can expect an output that shows each such image:

myapp           v1.0            d1a12345      3 weeks ago         500MB
myapp           v2.0            e3b54321      2 weeks ago         520MB

Once we’ve identified the images we want to remove, we can pipe the result to awk to extract the image IDs and then pass them to docker rmi:

$ docker rmi $(docker images | grep 'myapp' | awk '{print $3}')

This command removes all images that match the myapp pattern.

The above approach gives us more control over which images we remove. This enables us to target specific groups of images based on their names or tags.

4.4. Removing Unused (Dangling) Images

Unused or dangling images are those that no longer have any tags or are not associated with a running container. These images can pile up over time and take up valuable storage space.

We can use the docker image prune command, which clears out dangling images:

$ docker image prune

Furthermore, if we want to remove all unused images, including those with tags that are not in use by any containers, we add the -a option:

$ docker image prune -a

Additionally, to get a more thorough cleanup, including unused containers, volumes, and networks, we can replace image with system:

$ docker system prune -a

Further, regularly running these commands keeps a Docker environment lean and efficient.

5. Forcefully Removing Images and Containers

In certain situations, we need to take a more assertive approach to remove images or containers that are proving stubborn. This often happens when a container is actively running, or one or more containers still reference an image.

If we try to remove an image that’s in use, we typically see an error message:

$ docker rmi <image_id>
Error response from daemon: conflict: unable to remove repository reference "<image_id>" (must force) - container <container_id> is using its referenced image <image_id>

We also get a similar error when trying to remove a container in use:

$ docker rm <container_id>
Error response from daemon: cannot remove container "<container_id>": container is running: stop the container before removing or force remove

In these scenarios, the -f (force) option comes to the rescue. It ensures that the resources are deleted immediately.

To forcefully remove a running container, we use the respective switch with rm:

$ docker rm -f <container_id>

This command first stops the container and then removes it, regardless of its previous state.

Similarly, when we encounter an image that’s currently being used by one or more containers, we can force its removal:

$ docker rmi -f <image_id>

For both commands above, the -f flag ensures that Docker removes the resources without hesitation, even if they are currently in use. This can be dangerous, so caution is advised.

6. Conclusion

In this article, we explored various methods to remove Docker images and containers. We covered simple commands for removing single or multiple images, and strategies for forceful removal when necessary.

In conclusion, regular cleanup is essential for keeping a Docker environment efficient and organized.

2 Comments
Oldest
Newest
Inline Feedbacks
View all comments