Accessing kubernetes namespace (value) from inside a pod

8/4/2020

I am fairly new to kubernetes. Wanted to know if a program running inside a pod can access the namespace in which the pod is running.

Let me explain my usecase. There are two pods in my application's namespace. One pod has to be statefulset and must have atleast 3 replicas. Other pod (say POD-A) can be just a normal deployment. Now POD-A needs to talk to a particular instance of the statefulset. I read in an article that it can be done using this address format - <StatefulSet>-<Ordinal>.<Service>.<Namespace>.svc.cluster.local. In my application, the namespace part changes dynamically with each deployment. So can this value be read dynamically from a program running inside a pod?

Please help me if I have misunderstood something here. Any alternate/simpler solutions are also welcome. Thanks in advance!

-- aniztar
kubernetes

2 Answers

8/4/2020

https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/#the-downward-api has an example of this and more.

    env:
    - name: MY_POD_NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
-- coderanger
Source: StackOverflow

8/4/2020

You can get the namespace of a pod using the downward API : https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/#the-downward-api (mount the namespace as a environment variable).

Or , if a serviceAcount is mounted in the pod , the namespace the pod is living in can be found in the file: /var/run/secrets/kubernetes.io/serviceaccount/namespace.

-- Popopame
Source: StackOverflow