<p>I would like to know, how to find service name from the Pod Name in Kubernetes.</p>
<p>Can you guys suggest ?</p>

Big Bansal
<p>Services (<code>spec.selector</code>) and Pods (<code>metadata.labels</code>) are bound through shared labels.</p>
<p>So, you want to find all Services that include (some) of the Pod's labels.</p>
<pre class="lang-sh prettyprint-override"><code>kubectl get services \
--selector=${KEY-1}=${VALUE-1},${KEY-2}=${VALUE-2},...
--namespace=${NAMESPACE}
</code></pre>
<p>Where <code>${KEY}</code> and <code>${VALUE}</code> are the Pod's label(s) key(s) and values(s)</p>
<p>It's challenging though because it's possible for the Service's <code>selector</code> labels to differ from Pod labels. You'd not want there to be no intersection but a Service's labels could well be a subset of any Pods'.</p>
<p>The following isn't quite what you want but you may be able to extend it to do what you want. Given the above, it enumerates the Services in a Namespace and, using each Service's <code>selector</code> labels, it enumerates Pods that select based upon them:</p>
<pre class="lang-sh prettyprint-override"><code>
NAMESPACE=&quot;...&quot;

SERVICES=&quot;$(\
  kubectl get services \
  --namespace=${NAMESPACE} \
  --output=name)&quot;

for SERVICE in ${SERVICES}
do
  SELECTOR=$(\
    kubectl get ${SERVICE} \
    --namespace=${NAMESPACE}\
    --output=jsonpath=&quot;{.spec.selector}&quot; \
    | jq -r '.|to_entries|map(&quot;\(.key)=\(.value)&quot;)|@csv' \
    | tr -d '&quot;')
  PODS=$(\
    kubectl get pods \
    --selector=${SELECTOR} \
    --namespace=${NAMESPACE} \
    --output=name)
  printf &quot;%s: %s\n&quot; ${SERVICE} ${PODS}
done
</code></pre>
<blockquote>
<p><strong>NOTE</strong> This requires <a href="https://stedolan.github.io/jq/" rel="nofollow noreferrer"><code>jq</code></a> because I'm unsure whether it's possible to use <code>kubectl</code>'s <a href="https://kubernetes.io/docs/reference/kubectl/jsonpath/" rel="nofollow noreferrer">JSONPath</a> to range over a Service's labels <strong>and</strong> reformat these as needed. Even using <code>jq</code>, my command's messy:</p>
<ol>
<li>Get the Service's <code>selector</code> as <code>{&quot;k1&quot;:&quot;v1&quot;,&quot;k2&quot;:&quot;v2&quot;,...}</code></li>
<li>Convert this to <code>&quot;k1=v1&quot;,&quot;k2=v2&quot;,...</code></li>
<li>Trim the extra (?) <code>&quot;</code></li>
</ol>
</blockquote>
<p>If you want to do this for all Namespaces, you can wrap everything in:</p>
<pre class="lang-sh prettyprint-override"><code>NAMESPACES=$(kubectl get namespaces --output=name)
for NAMESPACE in ${NAMESPACE}
do
  ...
done
</code></pre>
