Kubernetes discover pods selected by a service

8/23/2018

I want to read information from a kubernetes cluster by API: I use fabric8 java client.

I want to know, which pods are selected by a service, but I cant find any linking information in objects except the name, which is not unique.

The other direction would be enough (service -> pods) or (pod <- service).

If one can help me with kubectl/yaml, I would probably find a way through the API on my own.

-- mdede
fabric8
kubectl
kubernetes

1 Answer

8/23/2018

Every Service has a corresponding Endpoints object. This isn’t super prominent in the main documentation, but it’s the object that has the list of everything the service actually points at.

One shell-oriented recipe that will give you the data:

kubectl get endpoints my-service-name -o json \
  | jq '.subsets[].addresses[].targetRef'

Its output includes, for each Pod targeted by the Service, its name and namespace. The containing EndpointAddress object also includes the pod private IP address and the name of the Node running the pod.

-- David Maze
Source: StackOverflow