部署规范和模板中的标签

Labels in Deployment Spec & template

在下面的 yaml 中:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  labels:
    app: my-nginx # Line 6
spec:             # Line 7  
  replicas: 2
  selector:
    matchLabels:
      app: my-nginx    # line 11
  template:
    metadata:
      labels:
        app: my-nginx   # Line 15
    spec:                # Line 16
      containers:
      - name: my-nginx
        image: nginx:alpine
        ports:
        - containerPort: 80
        resources:
          limits:
            memory: "128Mi" #128 MB
            cpu: "200m" #200 millicpu (.2 cpu or 20% of the cpu)

部署在第 6 行被赋予标签(app: nginx)。

第 7 行的部署规范使用第 16 行中提到的 Pod 规范


  1. selector 字段与 matchLabels 的用途是什么?

  2. template 字段与 labels 的用途是什么?

尝试添加评论来解释标签的作用:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
  labels:
    app: my-nginx # LABEL-A: <--this label is to manage the deployment itself. this may be used to filter the deployment based on this label. 
spec:              
  replicas: 2
  selector:
    matchLabels:
      app: my-nginx    #LABEL-B:  <--  field defines how the Deployment finds which Pods to manage.
  template:
    metadata:
      labels:
        app: my-nginx   #LABEL-C: <--this is the label of the pod, this must be same as LABEL-B
    spec:                
      containers:
      - name: my-nginx
        image: nginx:alpine
        ports:
        - containerPort: 80
        resources:
          limits:
            memory: "128Mi" #128 MB
            cpu: "200m" #200 millicpu (.2 cpu or 20% of the cpu)

LABEL-A: <--此标签用于管理部署本身。这可用于根据此标签过滤部署。 LABEL-A 的示例用法用于部署管理,例如过滤。

k get deployments.apps -L app=my-nginx

LABEL-B: <-- 必须有一些地方让复制控制器管理 pods。该字段定义 Deployment 如何找到要管理的 Pods。基于 pod 的这些标签,复制控制器确保它们准备就绪。

LABEL-C: <--这是pod的标签,LABEL-B用来监控。这必须与 LABEL-B

相同