这里介绍Kubernetes如何通过Downward API实现将Pod的元数据暴露、传递到容器当中
基于环境变量
通过Downward API可以将Pod的元数据暴露、传递给容器。特别有的元数据是无法在容器运行前得知的,比如Pod的IP、名称等。具体地,Downward API支持通过环境变量、Downward API类型卷两种方式。这里我们先演示Downward API通过环境变量的方式向容器传递元数据,示例配置如下所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| apiVersion: apps/v1 kind: ReplicaSet metadata: name: my-app-rs-1 spec: replicas: 1 selector: matchLabels: app: my-app-1 template: metadata: labels: app: my-app-1 spec: containers: - name: my-app-container-1 image: luksa/kubia resources: requests: cpu: 15m limits: memory: 40Mi env: - name: my_pod_name valueFrom: fieldRef: fieldPath: metadata.name - name: my_pod_ns valueFrom: fieldRef: fieldPath: metadata.namespace - name: my_pod_ip valueFrom: fieldRef: fieldPath: status.podIP - name: my_node_name valueFrom: fieldRef: fieldPath: spec.nodeName - name: my_cpu_request valueFrom: resourceFieldRef: resource: requests.cpu divisor: 1m - name: my_memory_limit valueFrom: resourceFieldRef: resource: limits.memory divisor: 1Mi
|
效果如下所示
这里补充说明下,对于容器资源请求、限制的环境变量而言,其值的计算方式为:资源请求、限制的实际值 / 基数单位。例如,容器内存限制为:40MB,基数单位为:1MB,则my_memory_limit的值为 40MB/1MB = 40
基于环境变量的方式下,存在两个缺陷:首先,无法暴露、传递Pod的标签、注解给容器。原因在于一旦标签、注解修改了,环境变量无法在不重启容器的前提下进行更新;其次,当前容器无法获取其所在Pod中其他容器的资源请求、限制信息。即容器只能获取其自身的资源请求、限制信息
基于Downward API类型卷
在通过Downward API类型卷方式将Pod的元数据暴露给容器时,不仅可以使得容器能够访问Pod的标签、注解信息,还可以访问其所在Pod的其他容器的资源、限制信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| apiVersion: apps/v1 kind: ReplicaSet metadata: name: my-app-rs spec: replicas: 1 selector: matchLabels: app: my-app template: metadata: labels: app: my-app author: AaronZhu annotations: buildEnv: dev buildDate: 2022.08.13 spec: containers: - name: my-app-container image: luksa/kubia resources: limits: cpu: 34m volumeMounts: - name: my-downward-volume mountPath: /Data/MyDownwardData volumes: - name: my-downward-volume downwardAPI: items: - path: myPodName fieldRef: fieldPath: metadata.name - path: myCpuLimit resourceFieldRef: containerName: my-app-container resource: limits.cpu divisor: 1m - path: myPodLabels fieldRef: fieldPath: metadata.labels - path: myPodAnnotations fieldRef: fieldPath: metadata.annotations
|
效果如下所示,符合预期
量纲词头
这里对于资源的请求、限制信息所使用的量纲词头,如下所示
1. 二进制词头
1 2 3 4 5 6
| Ki = 1024 = 2^10 Mi = 1024 * Ki = 2^20 Gi = 1024 * Mi = 2^30 Ti = 1024 * Gi = 2^40 Pi = 1024 * Ti = 2^50 Ei = 1024 * Pi = 2^60
|
2. 十进制词头
1 2 3 4 5 6 7
| k = 1000 = 10^3 M = 1000 * k = 10^6 G = 1000 * M = 10^9 T = 1000 * G = 10^12 P = 1000 * T = 10^15 E = 1000 * P = 10^18 m = 0.001 = 10^-3
|
参考文献
- Kubernetes in Action中文版 Marko Luksa著
- 深入剖析Kubernetes 张磊著