Downward API - Environment Variables

We can provide pod and containers field information to running containers using environment variables with the help of Downward API.

Following example shows how we can do that,

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: learning
spec:
  containers:
    - name: nginx
      image: nginx
      env:
        - name: POD_NAME
          valueFrom:
            fieldRef: 
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        

Once the pod is created, we can check if these environment variables have the right values.

root@nginx:/# printenv
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_SERVICE_PORT=443
HOSTNAME=nginx
POD_NAME=nginx
POD_NAMESPACE=learning
PWD=/
PKG_RELEASE=1~bookworm
HOME=/root
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
DYNPKG_RELEASE=1~bookworm
NJS_VERSION=0.8.10
TERM=xterm
SHLVL=1
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP_PORT=443
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
NGINX_VERSION=1.27.5
NJS_RELEASE=1~bookworm
_=/usr/bin/printenv

For containers fields, we can use access their resources section as shown below.

spec:
  containers:
    - name: nginx
      image: nginx
      env:
        - name: CPU_REQ
          valueFrom:
              resourceFieldRef:
                  containerName: nginx
                  resource: requests.cpu

If we do not specify resources information, downward API gives the value set by kubernetes.

References

  1. https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/