标签管理

· 标签是什么

-标签(Labels)是附加到 Kubernetes 对象上的键值对。

· 标签的用途

-k8s 在创建、删除、修改资源对象的时候可以使用标签来确定要修改的资源对象。在 Pod 调度的任务中,使用标签可以更加灵活的完成调度任务。

-标签可以在创建时附加到对象,也可以在创建之后随时添加和修改。标签可以用于组织和选择对象的子集。

· 管理标签语法格式

- 设置标签

kubectl label 资源类型 [资源名称] <key>=<value>

- 删除标签

kubectl label 资源类型 [资源名称] <key>-

- 查看标签

kubectl get 资源类型 [资源名称] --show-labels

- 使用标签选择

kubectl get 资源类型 [资源名称] -l <key>=<value>

• 使用 label 命令管理标签

# 查看标签

[root@master ~]# kubectl get pods --show-labels

NAME READY STATUS RESTARTS AGE LABELS

myhttp 1/1 Running 0 29s <none>

# 添加标签

[root@master ~]# kubectl label pods myhttp app=apache

pod/myhttp labeled

[root@master ~]# kubectl get pods --show-labels

NAME READY STATUS RESTARTS AGE LABELS

myhttp 1/1 Running 0 29s app=apache

# 删除标签

[root@master ~]# kubectl label pods myhttp app-

pod/myhttp labeled

[root@master ~]# kubectl get pods --show-labels

NAME READY STATUS RESTARTS AGE LABELS

myhttp 1/1 Running 0 31s <none>

· 资源文件设置标签

[root@master ~]# vim myhttp.yaml

---

kind: Pod

apiVersion: v1

metadata:

name: myhttp

labels: # 在配置文件中声明标签

app: apache # 定义标签,可以有多个

spec:

containers:

- name: apache

image: myos:httpd

[root@master ~]# kubectl replace --force -f myhttp.yaml

pod "myhttp" deleted

pod/myhttp created

[root@master ~]# kubectl get pods --show-labels

NAME READY STATUS RESTARTS AGE LABELS

myhttp 1/1 Running 0 7s app=apache

· 使用标签筛选资源对象

# 查询标签

[root@master ~]# kubectl get nodes --show-labels

NAME STATUS ROLES VERSION LABELS

master Ready control-plane v1.29.2 kubernetes.io/hostname=master

node-0001 Ready <none> v1.29.2 kubernetes.io/hostname=node-0001

node-0002 Ready <none> v1.29.2 kubernetes.io/hostname=node-0002

# 使用 -l 筛选标签

[root@master ~]# kubectl get nodes -l kubernetes.io/hostname=master

NAME STATUS ROLES AGE VERSION

master Ready control-plane 3h38m v1.29.2

Pod标签调度

· 标签选择运算符

- 与名称和 UID 不同, 标签不支持唯一性。通常,我们希望许多对象携带相同的标签。

- 通过标签选择算符,客户端/用户可以识别一组对象。

- 标签选择算符可以由多个需求组成。在多个需求的情况下,必须满足所有要求,相当于逻辑与(&&)运算符。

......

spec:

nodeSelector: # 在 Pod.spec 中声明标签选择运算符

key: value # 选择的标签

· 使用系统标签调度

– 查看 node-0002 的标签

[root@master ~]# kubectl get nodes --show-labels

NAME ...... LABELS

master ...... kubernetes.io/hostname=master

node-0001 ...... kubernetes.io/hostname=node-0001

node-0002 ...... kubernetes.io/hostname=node-0002

node-0003 ...... kubernetes.io/hostname=node-0003

· 通过标签调度Pod

[root@master ~]# vim myhttp.yaml

---

kind: Pod

apiVersion: v1

metadata:

name: myhttp

spec:

nodeSelector:

kubernetes.io/hostname: node-0002

containers:

- name: apache

image: myos:httpd

# 创建 Pod

[root@master ~]# kubectl replace --force -f myhttp.yaml

pod "myhttp" deleted

pod/myhttp created

# 查询调度节点

[root@master ~]# kubectl get pods -o wide

NAME READY STATUS RESTARTS AGE IP NODE

myhttp 1/1 Running 0 8s 10.244.2.11 node-0002

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐