在Kubernetes环境中,因为容器是被动态分配到节点上的,也就是说在容器启动之前,无法知道运行环境的具体信息
那如何在程序中获得当前容器的 pod ip 呢?又或者是 当前容器的 内存限制呢?
Kubernetes 使用 Downward API 通过环境变量和文件,将有关Pod的元数据注入到容器和集群中。
apiVersion: v1
kind: Pod
metadata:
name: getpodip
spec:
containers:
- image: nginx
name: getpodip
env:
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: MEM_LIMITS
valueFrom:
resourceFieldRef:
containerName: getpodip
resource: limits.memory
不过由于环境变量无法在容器启动之后更改,也可以将信息挂载到磁盘卷上,这样每次修改之后,程序可以通过重新读取文件内容,更新这些信息
apiVersion: v1
kind: Pod
metadata:
name: getpodip
spec:
containers:
- image: nginx
name: getpodip
volumeMounts:
- name: pod-info
mountPath: /pod-info
readOnly: true
- name: pod-resource
mountPath: /pod-resource
readOnly: true
volumes:
- name: pod-info
downwardAPI:
items:
- path: POD_IP
fieldRef:
fieldPath: metadata.name
- name: pod-resource
downwardAPI:
items:
- path: "cpu_limit"
resourceFieldRef:
containerName: getpodip
resource: limits.cpu
divisor: 1m
- path: "cpu_request"
resourceFieldRef:
containerName: getpodip
resource: requests.cpu
divisor: 1m
- path: "mem_limit"
resourceFieldRef:
containerName: getpodip
resource: limits.memory
divisor: 1Mi
- path: "mem_request"
resourceFieldRef:
containerName: getpodip
resource: requests.memory
divisor: 1Mi
不过不知道为什么这里 metadata.name 无法替换为 status.podIP
The Pod "getpodip" is invalid:
* spec.volumes[0].downwardAPI.fieldRef.fieldPath: Unsupported value: "status.podIP": supported values: "metadata.annotations", "metadata.labels", "metadata.name", "metadata.namespace", "metadata.uid"
* spec.containers[0].volumeMounts[0].name: Not found: "pod-info"
- Env vars using
valueFrom.fieldRef
:- spec.nodeName – the node’s name
- status.hostIP – the node’s IP
- metadata.name – the pod’s name
- metadata.namespace – the pod’s namespace
- status.podIP – the pod’s IP address
- spec.serviceAccountName – the pod’s service account name
- metadata.uid – the pod’s UID
- metadata.labels[”] – the value of the pod’s label (for example, metadata.labels[‘mylabel’])
- metadata.annotations[”] – the value of the pod’s annotation (for example, metadata.annotations[‘myannotation’])
- DownwardAPI volumes via items of
fieldRef
:- spec.nodeName – the node’s name
- status.hostIP – the node’s IP
- metadata.name – the pod’s name
- metadata.namespace – the pod’s namespace
- status.podIP – the pod’s IP address
- spec.serviceAccountName – the pod’s service account name
- metadata.uid – the pod’s UID
- metadata.labels- the value of the pod’s label (for example, metadata.labels[‘mylabel’])
- metadata.annotations – the value of the pod’s annotation (for example, metadata.annotations[‘myannotation’])