02 - Labels and Selectors
Q: How many PODs exist in the dev environment (env)?
$ kubectl get pods --selector env=dev
$ kubectl get pods --selector bu=finance --no-headers | wc -l
$ kubectl get pods --show-labels=true
Q: How many objects are in the prod environment including PODs, ReplicaSets and any other objects?
$ kubectl get all --selector env=prod
$ kubectl get all --selector env=prod --no-headers | wc -l
Q: Identify the POD which is part of the prod environment, the finance BU and of frontend tier?
$ kubectl get all --selector env=prod,bu=finance,tier=frontend
Q: Error Message
執行以下命令後,出現如下錯誤訊息。
$ kubectl apply -f replicaset-definition-1.yaml
The ReplicaSet "replicaset-1" is invalid: spec.template.metadata.labels: Invalid value: map[string]string{"tier":"nginx"}: `selector` does not match template `labels`
解析
這個標籤(template.metadata.labels)必須與 selector.matchLabels 一致,否則 ReplicaSet 無法正確匹配 Pod。
Update the replicaset-definition-1.yaml file as follows:
---
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: replicaset-1
spec:
replicas: 2
selector:
matchLabels:
tier: front-end
template:
metadata:
labels:
tier: front-end
spec:
containers:
- name: nginx
image: nginx 定義 Pod 的部分
```matchLabels(精確匹配)
這個 ReplicaSet 只會管理 tier: front-end 的 Pod。
```
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: frontend-replicaset
spec:
replicas: 3
selector:
matchLabels:
tier: front-end
template:
metadata:
labels:
tier: front-end
spec:
containers:
- name: nginx
image: nginx
```
※ 任何 擁有 tier: front-end 標籤 的 Pod,ReplicaSet 都會確保它的數量保持在 3 個。
※ 但如果 Pod 有 額外標籤(例如 tier: front-end, env: prod),仍然會被選擇。
matchExpressions(條件匹配)
- In(屬於某個集合)
- NotIn(不屬於某個集合)
- Exists(存在該標籤)
- DoesNotExist(不存在該標籤)

留言
張貼留言