K8S中的标签使用

标签可以用于管理Pod,对Pod进行分类处理,比如多个Pod运行多个MSC网元,另外多个Pod运行CUDB网元,那么可以给这些Pod指定Type标签,对于MSC网元的版本也可能不同,所以还可以指定Version标签。标签对于K8S中的可操作元素的归类和管理具有重要意义。

创建带标签的Pod

创建Pod时,将yaml文件加入Label字段,此处加入app叫myweb,ver版本为v2。使用kubectl create创建Pod。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
apiVersion: v1
kind: Pod
metadata:
name: myweb
labels:
app: myweb
ver: v2
spec:
restartPolicy: OnFailure
containers:
- name: myweb
image: mywebv1
imagePullPolicy: Never
ports:
- containerPort: 80
protocol: TCP

查看最新创建的Pod,

1
2
3
4
5
6
7
8
9
[root@master ~]# kubectl get pod -L app,ver
NAME READY STATUS RESTARTS AGE APP VER
myweb 1/1 Running 0 125m myweb v2
mywebv1 1/1 Running 1 14d

[root@master ~]# kubectl get pod --show-labels
NAME READY STATUS RESTARTS AGE LABELS
myweb 1/1 Running 0 126m app=myweb,ver=v2
mywebv1 1/1 Running 1 14d <none>

修改现有的Pod标签

使用指令kubectl label即可修改现有Pod的标签。例如,

1
2
3
4
5
6
7
8
9
10
11
12
[root@master ~]# kubectl label po mywebv1 app=myweb
Pod/mywebv1 labeled
[root@master ~]# kubectl get Pod -L app,ver
NAME READY STATUS RESTARTS AGE APP VER
myweb 1/1 Running 0 131m myweb v2
mywebv1 1/1 Running 1 14d myweb
[root@master ~]# kubectl label po mywebv1 ver=v1
Pod/mywebv1 labeled
[root@master ~]# kubectl get Pod -L app,ver
NAME READY STATUS RESTARTS AGE APP VER
myweb 1/1 Running 0 131m myweb v2
mywebv1 1/1 Running 1 14d myweb v1

按照指定的Label查看Pod

1
2
3
4
5
6
7
[root@master ~]# kubectl get po -l app=myweb --show-labels
NAME READY STATUS RESTARTS AGE LABELS
myweb 1/1 Running 0 134m app=myweb,ver=v2
mywebv1 1/1 Running 1 14d app=myweb,ver=v1

[root@master ~]# kubectl get po -l '!app' --show-labels
NAME READY STATUS RESTARTS AGE LABELS

按照指定的Label删除Pod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@master ~]# kubectl get po --show-labels
NAME READY STATUS RESTARTS AGE LABELS
my-nginx-86459cfc9f-fq7rt 1/1 Running 0 4h27m pod-template-hash=86459cfc9f,run=my-nginx
my-nginx-86459cfc9f-s282t 1/1 Running 0 4h27m pod-template-hash=86459cfc9f,run=my-nginx
myweb 1/1 Running 0 170m app=myweb,ver=v2
mywebv1 1/1 Running 1 14d app=myweb,ver=v1
mywebv3 1/1 Running 0 14m app=myweb,ver=v3

[root@master ~]# kubectl delete po -l app=myweb
pod "myweb" deleted
pod "mywebv1" deleted
pod "mywebv3" deleted

[root@master ~]# kubectl get po --show-labels
NAME READY STATUS RESTARTS AGE LABELS
my-nginx-86459cfc9f-fq7rt 1/1 Running 0 4h27m pod-template-hash=86459cfc9f,run=my-nginx
my-nginx-86459cfc9f-s282t 1/1 Running 0 4h27m pod-template-hash=86459cfc9f,run=my-nginx

给Node打Label

跟Pod操作一样,也可以给Node打标签,

1
2
3
4
5
6
7
[root@master ~]# kubectl label node nodeb gpu=true
node/nodeb labeled

[root@master ~]# kubectl get node --show-labels
NAME STATUS ROLES AGE VERSION LABELS
...
nodeb Ready <none> 18d v1.14.2 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,gpu=true ...

创建Pod时,选择指定标签的Node。

1
2
3
spec:
nodeSelector:
gpu: "true"