简体   繁体   中英

How to get all Kubernetes pod IP in each pods?

We have Kube.netes 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?

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 xyza and b.c.de

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

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.

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://kube.netes.io/docs/concepts/workloads/controllers/statefulset/#stable.network-id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM