deployment标签(labels)匹配相关知识:spec.selector.matchLables与spec.template.metadata.lables
Posted Locutus
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了deployment标签(labels)匹配相关知识:spec.selector.matchLables与spec.template.metadata.lables相关的知识,希望对你有一定的参考价值。
1. spec.selector.matchLables实验
1.1 正确的Deployment书写方式,是要让spec.selector.matchLabels值和spec.template.metadata.lables值完全匹配,这样才不会报错。
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
app: my-nginx
replicas: 2
template:
metadata:
labels:
app: my-nginx
spec:
containers:
- name: my-nginx
image: nginx
ports:
- containerPort: 80
创建pod成功
# kubectl get pods
NAME READY STATUS RESTARTS AGE
my-nginx-9b44d8f5-d6n8z 1/1 Running 0 3s
my-nginx-9b44d8f5-zzv52 1/1 Running 0 3s
1.2 如果不写spec.selector.matchLabels字段的内容,直接创建则会报错:缺少必要字段selector
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
replicas: 2
template:
metadata:
labels:
app: my-nginx
spec:
containers:
- name: my-nginx
image: nginx
ports:
- containerPort: 80
# kubectl create -f test_pod_svc.yaml
error: error validating "test_pod_svc.yaml": error validating data: ValidationError(Deployment.spec): missing required field "selector" in io.k8s.api.apps.v1.DeploymentSpec; if you choose to ignore these errors, turn validation off with --validate=false
1.3 当spec.selector.matchLabels匹配的键值,与spec.template.metadata.lables键值不相对应,也会直接报错:选择的和模板标签不匹配
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-nginx
spec:
selector:
matchLabels:
app: my-nginx-add
replicas: 2
template:
metadata:
labels:
app: my-nginx
spec:
containers:
- name: my-nginx
image: nginx:1.14
ports:
- containerPort: 80
# kubectl create -f test_pod_svc.yaml
The Deployment "my-nginx" is invalid: spec.template.metadata.labels: Invalid value: map[string]string"app":"my-nginx": `selector` does not match template `labels`
1.4 查看帮助手册
# kubectl explain Deployment.spec
selector <Object>
Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment.
pod的标签选择器。 由此选择其pod的现有ReplicaSet(副本集)将受此部署影响的副本。
2. 总结
-
在deployment.yaml中必须写spec.selector.matchLabels
-
在定义pod模板时,必须定义spec.template.metadata.lables,因为spec.selector.matchLabels是必须字段,而它又必须和spec.template.metadata.lables的键值一致。
-
spec.template.metadata.lables里面定义的内容,会应用到spec.template.spec下定义的所有pod副本中,在spec.template.spec.containers里面不能定义labels标签
3. 参考文章
https://cloud.tencent.com/developer/article/1394657
以上是关于deployment标签(labels)匹配相关知识:spec.selector.matchLables与spec.template.metadata.lables的主要内容,如果未能解决你的问题,请参考以下文章