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.
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
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=%
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}}'