Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes & Java: Retrieving Pod IPs behind Service

I have a Service in a Kubernetes cluster which has a label selector, several pods have this label, therefore are "connected" to the Service. Is it possible to retrieve the internal IP addresses of these pods using the Service IP?

I know that service endpoints can be retrieved in the Kubernetes CLI, however, I was wondering whether this could be achieved in Java? i.e., Nslookup.

Maybe an addition to this question would be: How do you perform a DNS query on a headless service, do you pass the service name?

Thanks,

like image 318
Yrneh Avatar asked Nov 24 '25 07:11

Yrneh


1 Answers

You can get the endpoints from the API server. For example to get the IP addresses for the first endpoint returned by the API server:

$ curl -s -k -H 'Authorization: Bearer <REDACTED>' \
  https://<apiserver-address>:6443/api/v1/endpoints | \
  jq .items[0].subsets[0].addresses[].ip

You can also use this to retrieve the node names where your pods are running calling the above endpoint.

$ curl -s -k -H 'Authorization: Bearer <REDACTED>' \
  https://<apiserver-address>:6443/api/v1/endpoints | \
  jq .items[0].subsets[0].addresses[].nodeName

This can also be done using your favorite language API like Java, Go and Python

Described here the SRV records that you can use to find the CLUSTER-IP address of your service (not your pods IP addresses). From a pod:

 $ dig srv _portname._tcp.servicename.default.svc.cluster.local
 ...
 servicename.default.svc.cluster.local. 5 IN A  10.x.x.x <== service IP
 ...
like image 133
Rico Avatar answered Nov 26 '25 22:11

Rico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!