为什么我必须多次显式定义标签?

Eks*_*psy 2 kubernetes

为什么需要多次定义部署的标签?为了快速解释我的问题,我举一个例子。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
# 1st Time
  labels:
    app: app
    tier: backend
spec:
  selector:
# 2nd Time
    matchLabels:
      app: app
      tier: backend
  template:
    metadata:
# 3rd time
      labels:
        app: app
        tier: backend
Run Code Online (Sandbox Code Playgroud)

我的第一个问题是我真的找不到任何spec.selector.matchlabels存在的充分理由。spec.selector.matchlabels 一定要匹配 spec.template.metadata.labels对吗?

描述:

Pod 的标签选择器。由此选择的 pod 的现有 ReplicaSet 将受到此部署的影响。它必须与 Pod 模板的标签匹配。

那么,如果它们应该固定为 kubernetes 知道的特定值,并且如果其中一个与另一个不匹配,无论如何都会抛出错误,那么为什么必须明确定义它们呢?


我的第二个问题可能有更合理的答案,那就是为什么必须明确定义部署的标签和模板的标签?它们不应该也相互匹配吗?或者是否存在它们可能不匹配的情况?我只是错误地使用它们吗?没有关于它们针对模板标签的使用的明确文档。:/

如果我可能做错或理解错误,请指出!:D

mda*_*iel 7

Why is there a need of defining one's deployment's labels multiple times?

Because they are for different audiences, and they do different things. That's usually the case for when you encounter something in computers that appears to be a duplicate

I'll skip to the tl;dr before answering the rest of your questions: if your deployments use the same values for all 3 labels, then you can use yaml anchors to stop the copy-paste:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels: &labels
    app: app
    tier: backend
spec:
  selector:
    matchLabels: *labels
  template:
    metadata:
      labels: *labels
Run Code Online (Sandbox Code Playgroud)

My first issue is that I really couldn't find any good reason for the spec.selector.matchlabels to exist at all. spec.selector.matchlabels must match spec.template.metadata.labels right?

The selector:matchLabels: must be a subset of the labels applied to the Pod, but they don't need to match exactly, otherwise it would limit the labels that could be applied to a Pod, since additional ones would then invalidate the matchLabels: and the Pod would no longer be managed by the Deployment.

我的第二个问题可能有更合理的答案,那就是为什么必须明确定义部署的标签和模板的标签?它们不应该也相互匹配吗?或者是否存在它们可能不匹配的情况?我只是错误地使用它们吗?没有关于它们针对模板标签的使用的明确文档。:/

部署标签是供您自己使用的元数据——据我所知,kubernetes 调度程序根本不会参考它们。Pod是调度的单位:其他一切都只是让 Kubernetescontroller-manager跟踪世界的期望状态。如果您希望能够快速识别“secops”团队创建的所有部署,您可以说kubectl get deploy -l team=secops,它会很高兴地给您返回列表。或者release=alpha,或者deployed-by=gitlab或者其他什么。这只是元数据。

模板数据是您定义应用于尚不存在的对象的标签的方式 -Deployment根据定义描述世界的未来状态,因此您需要描述创建事物时如何标记它们。然后,您需要能够描述被视为 的“成员”的所有 Pod 的集合Deployment。这都是可能的,我什至已经使用过几次,创建一个与现有Pod匹配的 Pod —— 在这种情况下,部署将接管这些 Pod 的责任,只要它们符合所描述的标准,Pod 调度中的任何内容都不会改变,但事实上,它们现在由 Deployment 拥有,并且 Deployment 会监督它们。Deploymentselector: