带tier: frontend标签的Kubernetes Pod创建后无法查询的原因排查
tier: frontend标签后Pod创建后无法查询到的原因分析 问题重现
尝试在Minikube中创建以下Pod:
apiVersion: v1 kind: Pod metadata: name: test-pod labels: tier: frontend spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 restartPolicy: OnFailure
执行创建命令后返回pod/test-pod created,但执行kubectl get pod无法找到该Pod,执行kubectl describe test-pod报错:error: the server doesn't have a resource type "test-pod"。
查看集群事件kubectl get event发现Pod的生命周期异常:
5m40s Normal Pulling pod/test-pod Pulling image "nginx:latest" 5m37s Normal Pulled pod/test-pod Successfully pulled image "nginx:latest" in 2.807s (2.807s including waiting) 5m37s Normal Created pod/test-pod Created container nginx 5m37s Normal Started pod/test-pod Started container nginx 2m41s Normal Killing pod/test-pod Stopping container nginx 20s Normal Scheduled pod/test-pod Successfully assigned default/test-pod to minikube
移除tier: frontend标签或替换为自定义标签mylabel: frontend时,Pod可正常创建并通过kubectl get pod查询到。
排查过程
- 尝试将标签值改为
tier: test,Pod可正常创建,但此时仍未明确原因。 - 进一步排查集群资源,发现存在一个ReplicaSet:
apiVersion: apps/v1 kind: ReplicaSet metadata: name: myapp-replicas labels: app: myapp tier: frontend spec: replicas: 3 selector: matchExpressions: - {key: tier, operator: In, values: [frontend, backend]} template: metadata: labels: app: myapp tier: frontend spec: containers: - name: nginx image: nginx ports: - containerPort: 80
移除该ReplicaSet后,带有tier: frontend标签的Pod可正常创建并查询。
原因解释
Labels本身仅作为对象的标识属性,不会直接对核心系统产生语义影响,但如果集群中存在**控制器资源(如ReplicaSet、Deployment等)**的selector匹配到这些标签,控制器会自动管理所有带有对应标签的Pod:
上述ReplicaSet的selector规则为tier标签值属于frontend或backend,且它的replicas设置为3,意味着它会维持集群中带有tier: frontend或tier: backend标签的Pod数量为3个。当手动创建带有tier: frontend标签的test-pod时,ReplicaSet会识别到这个Pod属于它的管理范围,此时集群中该标签的Pod数量超过了设定的3个,因此ReplicaSet会自动杀掉这个额外的Pod,导致无法通过kubectl get pod查询到它。
内容的提问来源于stack exchange,提问作者Bùi Đức Khánh

