How to Get Current Pod in Kubernetes Java Application
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
This worked for me.
podName = Optional.ofNullable(System.getenv("HOSTNAME"));
Every pod has a hostname
same as pod_name
. So what you can do is, write an api which return you hostname
.
Example:
in Javajava.net.InetAddress.getLocalHost();
in C#System.Environment.GetEnvironmentVariable("COMPUTERNAME");