Kubectl – get pods by image

A small tip mainly useful for troubleshooting the cluster — getting all pods that have containers with certain image.

This is not a trivial task because the pod does not connect to an image directly. Instead a pod has one or more containers which in turn are created from their own images.

Thankfully all this information is in the pod definition, so we can get it and format it.

Note that in most cases you don’t need to do it because for single-container-pods the convention is to include the name of the image in the pod. But for special cases here is the trick how to get it.

You need to have the kubectl installed. Run:

$ kubectl get pods --all-namespaces -o jsonpath="{range .items[*]}{.metadata.name}{' '}{.status.phase}{' '}{.spec.containers[*].image}{'\n'}{end}" | grep "<IMAGE_NAME>" | column -t -s " "


Create 2 pods from the same nginx image and retrieve them with a command:

$ kubectl run docs --image=nginx:1.17.8 --restart=Never
pod/docs created
$ kubectl run blog --image=nginx:1.16.1 --restart=Never
pod/blog created
$ kubectl get pods --all-namespaces -o jsonpath="{range .items[*]}{.metadata.name}{' '}{.status.phase}{' '}{.spec.containers[*].image}{'\n'}{end}" | grep "nginx" | column -t -s " "
blog  Running  nginx:1.16.1
docs  Running  nginx:1.17.8


The whole magic happens in the command:

kubectl get pods --all-namespaces -o jsonpath="{range .items[*]}{.metadata.name}{' '}{.status.phase}{' '}{.spec.containers[*].image}{'\n'}{end}"

It gets the json-s of all pods and allows you to filter interesting data from the pod definition using a jsonpath .

  • The {range .items[*] } lets you to iterate all the objects and glue the values from the same pod together.
  • The .metadata.name  and .status.phase  are the pieces of information we need.
  • .spec.containers[*].image  loops through all the containers, so if you have pods with multiple containers this command will glue them with a space.

The second part is just filtering and formatting the data, converting ” ” to the separator for the columns.

grep "nginx" | column -t -s " 

This is not an ideal way to do it but it’s pretty fast, easy to understand and works most of the times unless your image name is used in some other unrelated pods. In that case you can adjust the grep filter to exclude them.