How to get all Kubernetes pod IP in each pods?

9/22/2020

We have Kubernetes cluster where each service has 3 pod running. we got a use case where i want each pod knows the ip of other pods.

For Example:
P1 --> this pod should know ip of itself, p2, p3 pod ip's 
P2 --> this pod should know ip of itself, p1, p3 pod ip's 
p3 --> this pod should know ip of itself, p2, p3 pod ip's 

I found this on google but looks like we only get IP of pod itself it won't give the ip of other two pod running.

          - name: POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP

Is there a way i can get this info in my java code?

-- Mohit Singh
java
kubernetes
spring
spring-boot

3 Answers

9/22/2020

If you're looking for a solution that has deterministic destination address for a replica of pods, I'd probably go with a statefulset deployed with a headless service. Such a setup will give you intra cluster DNS address like pod-1,2,3.svc-name.default.cluster.local You could then use these DNS addresses to make pods talk to each other. https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#stable-network-id

-- tuxiedev
Source: StackOverflow

9/22/2020

Using env as you mentioned might not suffice as pods are supposed to be temporary resources and get added and deleted.

But below command can fetch you the values

$kubectl get pods -o=jsonpath="{range .items[*]}{.status.podIP}{','}{end}"

You did not mention if the pods belong to the same service but if that is the case(which I think), you could use Selectors

$kubectl get pods -l="app=my-service" -o=jsonpath="{range .items[*]}{.status.podIP}{','}{end}"
x.y.z.a,b.c.d.e,

Here the two IPs are x.y.z.a and b.c.d.e

You should be able to find equivalent in the corresponding language(java) api libraries

If you are okay to be able to let the request go to any pod, you can look at Kube DNS

-- Aditya Guru
Source: StackOverflow

9/22/2020

You can get the subsets of the endpoint to get all of pods IP. The endpoint has the same name as you svc. Using kubectl get ep ep-name -n your-ns -o yaml for details.

For Java code, you can use k8s java client(Officail/fabric lib) or access by k8s API.


Update:

kubectl get ep ep-name -n your-ns -o jsonpath='{range .subsets[*]}{range .addresses[*]}{.ip}{"\t"}{end}'

can get all pods IP. Using fabric8 lib you can reference this example

Endpoints endpoints = client.endpoints().inNamespace(namespace).withName("ep-name").get();
endpoints.getSubsets().getAddresses().forEach(endpointAddress -> log.info(endpointAddress.getIp()));

If your controller is StatefulSet, can use headless service to connect with other StatefulSet pods.

-- Leo
Source: StackOverflow