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

前端 未结 2 2020
难免孤独
难免孤独 2020-12-29 12:43

Is there a way to programmatically get the name of the pod that a container belongs to in Kubernetes? If so how? I\'m using fabric8\'s java client but curl or something simi

相关标签:
2条回答
  • 2020-12-29 13:16

    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
    
    0 讨论(0)
  • 2020-12-29 13:21

    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").

    0 讨论(0)
提交回复
热议问题