Filter images by dangling status
In this step, you will learn how to filter Docker images based on their "dangling" status. Dangling images are layers that have no relationship to any tagged images. They are often the result of building new versions of an image, which leaves the old layers without a tag. These dangling images consume disk space and can be cleaned up.
To filter images by their dangling status, you can use the --filter
flag with the dangling
key. The value can be true
to show only dangling images or false
to show only non-dangling images.
First, let's create a dangling image. We can do this by building a new image that replaces an existing one. We'll use a simple Dockerfile for this.
Create a file named Dockerfile
in your ~/project
directory with the following content:
FROM alpine
CMD ["echo", "Hello, world!"]
This Dockerfile is very simple. It uses the alpine
image as a base and just prints "Hello, world!" when a container is run from it.
Now, let's build an image from this Dockerfile and tag it.
Run the following command to build the image and tag it as my-image:latest
:
docker build -t my-image:latest .
You should see output indicating the build process:
[+] Building
...
Successfully built <image_id>
Successfully tagged my-image:latest
Now, let's modify the Dockerfile slightly and build it again with the same tag. This will create a new image with the my-image:latest
tag, and the previous image that had this tag will become dangling.
Edit the Dockerfile
in your ~/project
directory to change the command:
FROM alpine
CMD ["echo", "Hello again!"]
Now, build the image again with the same tag:
docker build -t my-image:latest .
You will see output similar to the previous build, but a new image ID will be generated. The previous image with the my-image:latest
tag is now dangling.
Let's list all images to see the dangling image.
Run the command:
docker images
You might see an image with <none>
in the REPOSITORY and TAG columns. This is a dangling image.
REPOSITORY TAG IMAGE ID CREATED SIZE
my-image latest <new_image_id> <created_time> <size>
<none> <none> <old_image_id> <created_time> <size>
hello-world latest <image_id> <created_time> <size>
Now, let's filter to show only the dangling images using the --filter dangling=true
flag.
Run the command:
docker images --filter dangling=true
You should see only the dangling image:
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> <old_image_id> <created_time> <size>
To see only non-dangling images, you can use --filter dangling=false
.
Run the command:
docker images --filter dangling=false
This will list all images that are not dangling:
REPOSITORY TAG IMAGE ID CREATED SIZE
my-image latest <new_image_id> <created_time> <size>
hello-world latest <image_id> <created_time> <size>
This demonstrates how to filter images based on their dangling status.