Labels在现实中可以对事物进行分类。例如动物的分类是猫、狗;颜色是绿色或红色。
Selectors为了选择出特定的Label,例如指定一只绿色的猫
,就能确定一个唯一的动物。
在k8s里,我们可以各种Pods打标签:
K8S里的label和aws的label在形式上一模一样,以key:value
这种形式存在。一般用于deployment
和service
分为两种情况:用cli
设置label、在yaml里设置label。
先创建两个pod:
kubectl run nginx --image=nginx
kubectl run nginx2 --image=nginx
设置label:
kubectl label pod nginx-7cdbd8cdc9-hh8ks env=prod
kubectl label pod nginx2-dbf77bdb7-6j8ts env=dev
根据label查询:
[@root:kubernetes]$ kubectl get pod -l env=dev
NAME READY STATUS RESTARTS AGE
nginx2-dbf77bdb7-6j8ts 1/1 Running 0 67m
# 可以用!=查询
[@root:kubernetes]$ kubectl get pod -l env!=dev
NAME READY STATUS RESTARTS AGE
frontend-74b4665db5-crvbg 1/1 Running 0 127d
frontend-74b4665db5-lwzxn 1/1 Running 0 127d
frontend-74b4665db5-v9s7j 1/1 Running 0 127d
frontend-74b4665db5-xmrwh 1/1 Running 0 127d
mycontainer 1/1 Running 0 13h
nginx-7cdbd8cdc9-hh8ks 1/1 Running 0 69m
redis-master-6fbbc44567-jj8kt 1/1 Running 0 127d
redis-slave-74ccb764fc-j8vsx 1/1 Running 0 127d
redis-slave-74ccb764fc-vljl6 1/1 Running 0 127d
使用metadata.labels
设置标签:
apiVersion: v1
kind: Pod
metadata:
name: mycontainer
labels:
env: "prod"
owner: kongpingfan
spec:
containers:
- image: "mykplabs/kubernetes:nginx"
name: "nginxxx"
[@root:pod]$ kubectl get pods -l env=prod
NAME READY STATUS RESTARTS AGE
mycontainer 1/1 Running 0 13h
nginx-7cdbd8cdc9-hh8ks 1/1 Running 0 72m
除了-l
外,也可以使用--selector
参数选择出特定的pods:
kubectl get pods --selector app=web-01
如果想获取具有某个标签的所有对象,可以运行:kubectl get all --selector xxx=xxxxx
master $ kubectl get all --selector env=prod
NAME READY STATUS RESTARTS AGE
pod/app-1-zzxdf 1/1 Running 0 4m
pod/app-2-xhkbg 1/1 Running 0 4m
pod/auth 1/1 Running 0 4m
pod/db-2-jz2xk 1/1 Running 0 4m
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/app-1 ClusterIP 10.105.247.17 <none> 3306/TCP 4m
NAME DESIRED CURRENT READY AGE
replicaset.apps/app-2 1 1 1 4m
replicaset.apps/db-2 1 1 1 4m
资源可能具有多个label,一次查询多个label时,有两种方式:
kubectl get all --selector env=prod,bu=finance,tier=frontend
或:
kubectl get pods --selector env=prod --selector bu=finance --selector tier=frontend