I am deploying my Microservices on Kubernetes Cluster. Every Application has 4 replicas or PODS. For a REST API in 1 application, I want to track which POD addressed my request. e.g. my /app/deploy(body contains app_id)
request is handled by POD1
.
For the same, I have imported Kubernetes jar in my application. In my code, I want to check the current POD on which this code is running. I want an API like kubernetesDiscoveryClient.getCurrentPOD()
, something of this sort.
You do not need Kubernetes Jar in your Java application. A simple System.getenv("HOSTNAME")
will give you the name of your Pod. Works on all platform, and since Kubernetes version 1.6 at least.
More formally, you could use the following in your Kube spec (detailed reference), and then read the environment using System.getenv("MY_POD_NAME")
in Java.
env:
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
Every pod has a hostname
same as pod_name
. So what you can do is, write an api which return you hostname
.
Example:
in Java java.net.InetAddress.getLocalHost();
in C# System.Environment.GetEnvironmentVariable("COMPUTERNAME");
This worked for me.
podName = Optional.ofNullable(System.getenv("HOSTNAME"));