kubernetes pod yaml set as env var the pod ip and port

3/21/2020

I have a case where i'd like to set the IP address of the pod as part of the container environment variables as well as the port (which can be hardcoded to default8080 for example)

something like below but I need to append the port as part of that too. so that APPLICATION_SERVER would result as 111...000:8080 something like this i guess.

        - name: APPLICATION_SERVER
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
-- tosi
kubernetes

2 Answers

3/22/2020

That information is available in the Downward API

The Values you are looking are available as env vars from the Downward API

  • status.podIP - the pod’s IP address
  • spec.serviceAccountName - the pod’s service account name
  • spec.nodeName - the node’s name
  • status.hostIP - the node’s IP

Podspec

apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c"]
      args:
      - while true; do
          echo -en '\n';
          echo "Application Server $(APPLICATION_SERVER)";
          sleep 10;
        done;
      env:
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: APPLICATION_SERVER
          value: "$(MY_POD_IP):8080"

Output

kubectl logs dapi-envars

Application Server 10.244.0.7:8080

Application Server 10.244.0.7:8080

Application Server 10.244.0.7:8080

Application Server 10.244.0.7:8080

Application Server 10.244.0.7:8080

https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/

-- strongjz
Source: StackOverflow

3/21/2020

You can reuse defined environment variables to define new ones. For example, in your case you can do something like that:

- name: POD_IP
  valueFrom:
    fieldRef:
      fieldPath: status.podIP
- name: APPLICATION_SERVER
  value: "$(POD_IP):8080"

Make sure that APPLICATION_SERVER declared after POD_IP, otherwise this will not work.

-- Grigoriy Mikhalkin
Source: StackOverflow