Programmatically get the name of the pod that a container belongs to in Kubernetes?

白昼怎懂夜的黑 提交于 2019-11-30 14:06:03

You can tell Kubernetes to put the pod name in an environment variable of your choice using the downward API.

For example:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: gcr.io/google_containers/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
  restartPolicy: Never

The pod name is written to /etc/hostname so it's possible to read it from there. In Java (which I'm using) you can also get the hostname (and thus the name of the pod) by calling System.getenv("HOSTNAME").

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!