docker,

Filter the output of docker image ls

Aug 26, 2021 · 2 mins read · Post a comment
Filter the output of docker image ls

Sometimes using the filter flag as a part of the docker image ls command can be useful to figure out which images are taking space, which are dangling images or unused. In this tutorial, I’m going to show you some useful scenarios on how can you use the --filter flag to filter the list of images.

Prerequisites

  • Docker installed

Filter only dangling images

The following example will only return dangling images:

sudo docker image ls --filter dangling=true

Output:

REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
<none>        <none>    4fd34165afe0   2 days ago     14.5MB

Docker currently supports the following filters:

  • dangling: Accepts true or false , and returns only dangling images (true), or non-dangling images (false).
  • before: Requires an image name or ID as argument, and returns all images created before it.
  • since: Same as above, but returns images created after the specified image.
  • label: Filters images based on the presence of a label or label and value. The docker image ls command does not display labels in its output.

Display only images tagged as latest

Here’s an example using reference to display only images tagged as latest:

sudo docker image ls --filter=reference="*:latest"

Output:

REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
debian        latest    fe3c5de03486   9 days ago     124MB
amazonlinux   latest    d85ab0980c91   3 weeks ago    163MB
ubuntu        latest    9873176a8ff5   2 months ago   72.7MB
wordpress     latest    c01290f258b3   4 months ago   550MB
nginx         latest    62d49f9bab67   4 months ago   133MB

Return the size property of images on a Docker host

You can use the --format flag to format output using Go templates:

sudo docker image ls --format "{{.Size}}"

Output:

124MB
163MB
227MB
72.7MB

Return all images, but only display repo, tag and size

if you want to return all images with repo, tag and size only, use the following command:

sudo docker image ls --format "{{.Repository}}: {{.Tag}}: {{.Size}}"

Output:

debian: latest: 124MB
amazonlinux: latest: 163MB
rockylinux/rockylinux: latest: 227MB
ubuntu: latest: 72.7MB
mysql: 5.7: 447MB
wordpress: latest: 550MB
nginx: latest: 133MB

Conclusion

There are a lot of complex scenarios on how to filter the output of the docker image ls. Here I showed you the basic ones, but you can always use the Linux commands such as grep and awk to filter more specified outputs. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on telegram.