<p>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.</p>

Arghya Sadhu
<p>There are two ways to list the pods behind a service. </p>

<p><strong>The easier way but with two commands</strong></p>

<p>Find the selector by running the below command</p>

<pre><code>kubectl get services -o=wide
</code></pre>

<p>Output:</p>

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

<p>Pass the selector to the command below</p>

<pre><code>kubectl get pods --selector=run=nginx -o=name
</code></pre>

<p>To see the exact pod names without <code>pod/</code></p>

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

<p><strong>In a single command but using the endpoints information for the service <code>hello-world-service</code></strong></p>

<pre><code>kubectl get endpoints hello-world-service -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
</code></pre>
