How to list names of all pods serving traffic behind a service in kubernetes

2/14/2020

I want to list names of all pods which are actually serving traffic behind a kubernetes service.My question is how to achieve this by executing a single kubectl command.

-- Arghya Sadhu
kubernetes

3 Answers

2/14/2020

This should work, "-o=name" is for displaying only pod name.

kubectl get pods -o=name --all-namespaces | grep {service-name}

Replace {service-name} with your service name

-- Rahul Goel
Source: StackOverflow

2/14/2020

This command worked

kubectl get ep servicename -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | xargs -I % kubectl get pods -o=name --field-selector=status.podIP=%
-- Arghya Sadhu
Source: StackOverflow

2/14/2020

There are two ways to list the pods behind a service.

The easier way but with two commands

Find the selector by running the below command

kubectl get services -o=wide

Output:

NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE   SELECTOR
hello-world-service   ClusterIP   172.21.xxx.xx   <none>        80/TCP    13m   run=nginx

Pass the selector to the command below

kubectl get pods --selector=run=nginx -o=name

To see the exact pod names without pod/

kubectl get pods --selector=run=nginx  --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'

In a single command but using the endpoints information for the service hello-world-service

kubectl get endpoints hello-world-service -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
-- Vidyasagar Machupalli
Source: StackOverflow