I am trying to deploy my application using helm charts. I have defined a statefulSet as a kind under deployment.yaml and provided a headless service under spec.serviceName. Code snippet from deployment.yaml is given below.
Post deployment, when I fire "kubectl get pods", its shows POD name as "MyApp-100-deployment-n" where n >=0, based on replicas.
If I go inside the pod using kubectl exec, and fire "hostname" command , I get "MyApp-100-deployment-n" as hostname and when I fire "hostname --fqdn" , I get something like below:
MyApp-100-deployment-n.<name of Service>.<Namespace>.svc.cluster.local
These results are fine and good but when my application written in JAVA and which is deployed now tries to get the hostname using InetAddress.getLocalHost().getHostName()
, It gets the entire fqdn of pods , not the hostname of pod. This is something which is bothering me. Why Java InetAddress is not able to get the hostname only? Is there any way related to configuration in yaml files to not allow the headless service to modify the hostnames? Eventually, I need only hostname not fqdn in Java code to do processing.
If I remove the headless service name from the deployment.yaml and deploy the application and fire the hostname and hostname --fqdn command from inside the container, I get only "MyApp-100-deployment-n" as results for both. Adding the headless service is only introducing the fqdn.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: "{{ .Chart.Name }}-{{ .Chart.AppVersion | replace "." "" }}-deployment"
labels:
app: Myapp-deployment
{{ include "metadata.labels.standard" . | indent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app: "{{ .Chart.Name }}-{{ .Chart.AppVersion | replace "." "" }}"
serviceName: "{{ .Chart.Name }}-{{ .Chart.AppVersion | replace "." "" }}"
You can use the env variable HOSTNAME
that is present on each container and gives you only the hostname.
Also, try to execute env on any pod to see all available variables
kubectl exec <pod-name> env
An explanation of why using InetAddress.getLocalHost().getHostName()
is not the right way of retrieving the hostname is here