in

How to List and Remove Docker Images? An In-Depth Practical Guide

default image

As a DevOps engineer and Docker power user, I often need to manage the Docker images on my systems. Listing and removing Docker images efficiently is an essential skill for anyone working with Docker.

In this comprehensive, hands-on guide, I‘ll share my knowledge and experience to help you master Docker image management.

Why Image Management Matters

First, let‘s discuss why properly managing Docker images is so important.

Based on my experience managing containerized environments, here are some key reasons:

  • Saves disk space: Docker images, layers, and containers can consume significant disk space. Removing old and unused images helps free up space.

  • Avoids clutter: Having too many accumulated Docker images makes it harder to work efficiently. Pruning old images declutters.

  • Security: Old images may contain vulnerabilities. Removing unneeded images reduces your exposure.

  • Performance: Docker can slow down with hundreds of images. Pruning improves caching and load times.

  • Build efficiency: Removing intermediate build images avoids re-building unchanged layers.

According to Docker‘s 2021 container adoption survey, 52% of Docker users say minimizing storage is a major consideration. So proper image management clearly matters to the majority of Docker users.

Listing Docker Images

Now let‘s dive into the key commands and techniques for listing and finding information about your Docker images.

docker images – List Images

The docker images command shows all top-level images installed on your Docker host:

$ docker images

REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
nginx        latest    0d409d33b27a   3 days ago      133MB
python       3.8       b3f0d57c53e9   3 weeks ago     898MB 
alpine       latest    b7b28af77ffe   6 weeks ago     5.59MB

From this default output, we can see the image repository name, tags, unique image IDs, creation date, and size on disk.

Based on my experience, here are some points worth noting about the image sizes shown:

  • The size reflects the cumulative space taken up by the image and all its parent layers.

  • The size listed for an image is its true size on disk only if the image has a single tag.

  • If an image has multiple tags, its size will show for each tag but only use real disk space once.

  • Saving the image contents using docker save results in a .tar file equal to this size.

So in summary, the docker images sizes represent the total virtual size of an image, which only uses real disk space once regardless of how many tags it has.

Listing Recent Images

The default docker images output shows the images in order from most recent to oldest. So the top images in the list represent your most recently pulled or built images.

List by Repository and Tag

You can filter the docker images output by repository name:

$ docker images python

REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
python       3.8       b3f0d57c53e9   3 weeks ago    898MB

And also by a specific repository tag combination:

$ docker images python:3.8

REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
python       3.8       b3f0d57c53e9   3 weeks ago    898MB

This allows you to narrow down the images shown to those you care about.

List Full Image IDs

By default, docker images only shows a partial prefix of the full image ID:

$ docker images 

REPOSITORY   TAG       IMAGE ID          
nginx        latest    0d409d33b27a
python       3.8       b3f0d57c53e9

The full image IDs are much longer, as you can see with the --no-trunc flag:

$ docker images --no-trunc

REPOSITORY   TAG        IMAGE ID                                                                  
nginx        latest     sha256:0d409d33b27a03a388311d8eea70aa667893bffe1b71a25d9ef1e04767e65873
python       3.8        sha256:b3f0d57c53e97a2733566b184f5b0bf8132282919289528a5d2f4a6815d29230

These long unique image IDs can sometimes be useful for scripting and automation. The shortened ID is easier for humans to read though.

List Image Digests

For images using Docker schema V2 or higher, a content-addressable digest is generated:

$ docker images --digests

REPOSITORY   TAG       DIGEST                                                                    IMAGE ID      CREATED      SIZE
nginx        latest    sha256:aeaee28773903bdd5d051e27438ed329ea074dc967d3fd24ae0d19697f339aac   0d409d33b27a 3 days ago    133MB
python       3.8       sha256:401baa5d2cc779b296b3a88c04b83c73799a4abc2d5b1425bbd19f7db05573ac   b3f0d57c53e9 3 weeks ago   898MB  

This digest uniquely identifies the image contents and is especially useful for potentially ambiguous tags like latest. I typically use digests for reliable automation in CI/CD pipelines.

Filtering Image Lists

Listing all images isn‘t always enough. Often you need to filter the docker images output for specific use cases.

The --filter flag allows filtering images by:

  • dangling=true – show dangling images not tagged
  • label – by label key/value pairs
  • before – images created before specified id/reference
  • since – images created since specified id/reference
  • reference – images that match a reference pattern

For example, to show images created in the last week:

$ docker images --filter "since=nginx:latest" 

REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
python       3.8       b3f0d57c53e9   3 weeks ago    898MB

Multiple filters can be combined, like:

$ docker images --filter "label=tier=backend" --filter "before=python:3.8"

This flexible filtering makes it easy to drill down into just the images you need to investigate.

Formatting Image Lists

For scripting and programmatic use, the ability to customize the image listing output is very valuable.

The --format flag supports Go template formatting with image metadata placeholders:

Placeholder Description
.ID Image ID
.Repository Image repository
.Tag Image tag
.Digest Image digest
.CreatedAt Image creation date/time
.Size Image size on disk

For example, to print just the image IDs and repository name:

$ docker images --format "{{.ID}}: {{.Repository}}"

0d409d33b27a: nginx
b3f0d57c53e9: python 
b7b28af77ffe: alpine

Formatting the output from docker images helps when building shell scripts or other tooling around Docker.

Removing Docker Images

Now that we‘ve covered listing Docker images in depth, let‘s look at how to remove and delete images you no longer need.

docker image rm

The docker image rm command deletes one or more images by repository and tag:

$ docker image rm python:3.8

Untagged: python:3.8
Untagged: python@sha256:401baa5d2cc779b296b3a88c04b83c73799a4abc2d5b1425bbd19f7db05573ac  
Deleted: sha256:b3f0d57c53e97a2733566b184f5b0bf8132282919289528a5d2f4a6815d29230

This untags the image and removes it as long as it has no other tags.

You can remove multiple images by passing multiple repo/tag names:

$ docker image rm nginx:latest python:3.8

Untagged: nginx:latest
Untagged: nginx@sha256:aeaee28773903bdd5d051e27438ed329ea074dc967d3fd24ae0d19697f339aac  
Deleted: sha256:0d409d33b27a03a388311d8eea70aa667893bffe1b71a25d9ef1e04767e65873

Untagged: python:3.8
Untagged: python@sha256:401baa5d2cc779b296b3a88c04b83c73799a4abc2d5b1425bbd19f7db05573ac
Deleted: sha256:b3f0d57c53e97a2733566b184f5b0bf8132282919289528a5d2f4a6815d29230

Force Removing Images

If you attempt to remove an image that is in use by a running container, it will fail:

$ docker image rm nginx 

Error: 
conflict: unable to remove repository reference "nginx" (must force) - container e289a51a932b is using its referenced image 0d409d33b27a

In this case, you can either stop the dependent containers first, or use the -f flag to force the removal:

$ docker image rm -f nginx

Untagged: nginx:latest
Untagged: nginx@sha256:aeaee28773903bdd5d051e27438ed329ea074dc967d3fd24ae0d19697f339aac  
Deleted: sha256:0d409d33b27a03a388311d8eea70aa667893bffe1b71a25d9ef1e04767e65873

However, force removing images in use by containers will cause those containers to fail, so use this carefully.

Pruning Dangling Images

When building and rebuilding images, "dangling" intermediate layers and images often get left behind, wasting disk space:

$ docker images

<none>              <none>              f5283438590d        19 hours ago        137MB
<none>              <none>              578fafb77ab3        19 hours ago        145MB

The docker image prune command safely removes these dangling images:

$ docker image prune 

WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y

Deleted Images:
untagged: <none>:<none> 
deleted: sha256:f5283438590dc561f908faeafbd5a3c658fadc97af3c37612e870cabb153cn38 
deleted: sha256:578fafb77ab369e18457129951c3823f5f14eae5c9f0d8c805ed534d50a5325e

Total reclaimed space: 282MB

This can reclaim significant amounts of disk space by cleaning up build cache layers.

Removing Unused Images

By default, docker image prune only removes dangling images not tagged or used by containers.

Adding the -a flag also removes any images not currently associated with a container, excluding them from prune:

$ docker image prune -a

WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y

Deleted Images:
untagged: alpine:3.9
deleted: sha256:191eb1ca3eb116c25e1922b56a448d6f114c657be9c9d954838390eb355a290e
deleted: sha256:796166d82a694d8c23908d6f56791d391315e88de2b3d635eba380c6d276a54d  

untagged: debian:jessie 
deleted: sha256:f5029279ec1223b70f2c8c8c10aeec905dd26298b6f1c0cc55e9cafca0ee8303
deleted: sha256:1c35c1915c3b82833d5e8a97a1faa2587c26f0563a5459c2b53c1204f3d0f339

Total reclaimed space: 976MB

So this removes images without containers, great for cleaning up after Dockerfile testing.

Use -a together with --force to bypass the confirmation prompt when pruning all images.

Stop and Remove Containers and Images

A common scenario when cleaning up a Docker host is removing all containers and images to start fresh.

This can be done with docker rm to remove containers and docker rmi to remove images:

# Stop all running containers
$ docker rm -vf $(docker ps -a -q)

# Remove all images  
$ docker rmi -f $(docker images -a -q)

The docker ps -a -q and docker images -a -q commands output only the numeric IDs which are passed into docker rm and docker rmi to efficiently delete everything.

Adding the -f flag forces removal without a confirmation prompt needed for each image/container.

Garbage Collection

An alternative to manually removing images is Docker‘s built-in garbage collection.

The docker system prune command will:

  • Remove all dangling/unused images
  • Remove unused containers, volumes, networks and build cache

Garbage collection frees up space while preserving tagged images and containers in use.

By default it prompts for confirmation before removing anything. This can be bypassed with flags:

$ docker system prune -a --force

tips for Docker Image Management

Here are some best practices I‘ve learned for managing Docker images efficiently from my experience:

  • Tag images logically – Use tags like versions, dates, or Git SHA ids to make cleanup easier. Avoid latest tags.

  • Delete intermediate build images – Compile your Dockerfiles to avoid leaving around build cache layers and unnamed images.

  • Remove unused images weekly – Cleanup old experiments, temporary images etc on a schedule with docker image prune.

  • Monitor disk usage – Keep tabs on how much space Docker is using with docker system df and stay under 70-80% for best performance.

  • Use image digests in production – Digest IDs like nginx@sha256:d021...7a86 avoid issues with environment inconsistencies and mutable tags.

  • Limit image variety – Consolidate on standardized base images like Ubuntu, Alpine, etc and avoid image sprawl.

  • Integrate into CI/CD pipelines – Automatically build, push, pull, and clean up Docker images in your CI/CD workflow.

Conclusion

I hope this guide has helped demystify the process for listing and removing Docker images on your system.

Here‘s a quick recap of what we covered:

  • Use docker images to list images and filter/format the output
  • Remove images with docker image rm and docker rmi using tags or IDs
  • Prune dangling and unused images to clean up disk space
  • Force remove images using -f flag
  • Stop containers and delete all images to easily reset environment
  • Follow best practices like tagging logically and pruning often

Mastering Docker image management will save you disk space, improve security, and boost productivity. Let me know if you have any other Docker tips or questions!

Written by