kubernetes-downwardAPI简介与实践(12)

关山初度尘未洗,策马扬鞭再奋蹄!这篇文章主要讲述kubernetes-downwardAPI简介与实践(12)相关的知识,希望能为你提供帮助。
一、downwardAPI简介
【kubernetes-downwardAPI简介与实践(12)】1、downwardAPI存储卷类型,从严格意义上来说,downwardAPI不是存储卷,它自身就存在,原因在于,它引用的是Pod自身的运行环境信息,这些信息在Pod启动手就存在。
2、类似于ConfigMap或Secret资源,容器能够在环境变量中在valueFrom字段中嵌套fieldRef或resourceFieldRef字段来引用其所属Pod对象的元数据信息。
不过,通常只有常量类型的属性才能够通过环境变量注入到容器中,毕竟,在进程启动完成后无法再向其告知变量值的变动,于是,环境变量也就不支持中途的更新操作。容器规范中可在环境变量配置中的valueFrom通过内嵌字段fieldRef引用的信息包括如下这些:

metadata.name:Pod对象的名称;

metadata.namespace:Pod对象隶属的名称空间;

metadata.uid:Pod对象的UID;

metadata.labels[< KEY> ]:Pod对象标签中的指定键的值,例如metadata.labels[mylabel],仅Kubernetes 1.9及之后的版本才支持;

metadata.annotations[< KEY> ]:Pod对象注解信息中的指定键的值,仅Kubernetes 1.9及之后的版本才支持。

3、容器上的计算资源需求和资源限制相关的信息,以及临时存储资源需求和资源限制相关的信息可通过容器规范中的resourceFieldRef字段引用,相关字段包括requests.cpu、limits.cpu、requests.memory和limits.memory等。另外,可通过环境变量引用的信息有如下几个:
status.podIP:Pod对象的IP地址

spec.serviceAccountName:Pod对象使用的ServiceAccount资源名称

spec.nodeName:节点名称

status.hostIP:节点IP地址

4、另外,还可以通过resourceFieldRef字段引用当前容器的资源请求及资源限额的定义,因此它们包括requests.cpu、requests.memory、requests.ephemeral-storage、limits.cpu、limits.memory和limits.ephemeral-storage这6项。
二、downwardAPI实践
1、通过fieldRef传递示例:
apiVersion: v1
kind: Pod
metadata:
name: downwardapi-env-demo
labels:
app: demoapp
spec:
containers:
- name: demoapp
image: ikubernetes/demoapp:v1.0
command: [ "/bin/sh", "-c", "env" ]
resources:
requests:
memory: "32Mi"
cpu: "250m"
limits:
memory: "64Mi"
cpu: "500m"
env:
- name: THIS_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: THIS_POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: THIS_APP_LABEL
valueFrom:
fieldRef:
fieldPath: metadata.labels[app]
- name: THIS_CPU_LIMIT
valueFrom:
resourceFieldRef:
resource: limits.cpu
- name: THIS_MEM_REQUEST
valueFrom:
resourceFieldRef:
resource: requests.memory
divisor: 1Mi
restartPolicy: Never #从不重启

2、通过downwardAPI传递:
kind: Pod
apiVersion: v1
metadata:
name: downwardapi-volume-demo
labels:
zone: zone1
rack: rack100
app: demoapp
annotations:
region: ease-cn
spec:
containers:
- name: demoapp
image: ikubernetes/demoapp:v1.0
resources:
requests:
memory: "32Mi"
cpu: "250m"
limits:
memory: "64Mi"
cpu: "500m"
volumeMounts:
- name: podinfo
mountPath: /etc/podinfo
readOnly: false
volumes:
- name: podinfo
downwardAPI:
defaultMode: 420
items:
- fieldRef:
fieldPath: metadata.namespace
path: pod_namespace#会生成path指定的文件名,里面包含键值
- fieldRef:
fieldPath: metadata.labels
path: pod_labels
- fieldRef:
fieldPath: metadata.annotations
path: pod_annotations
- resourceFieldRef:
containerName: demoapp
resource: limits.cpu
path: "cpu_limit"
- resourceFieldRef:
containerName: demoapp
resource: requests.memory
divisor: "1Mi"
path: "mem_request"


    推荐阅读