Pod 亲和性、反亲和性调度

Pod 亲和性调度

节点亲和性调度和Pods 亲和性调度都可以实现,让一组相关的Pod运行在特定的一个或者一些主机上

但是,Pod 亲和性调度相比于节点亲和性调度更灵活,前者需要配合标签完成,而后者则不需要,所以更加灵活简便

apiVersion: v1
kind: Pod
metadata:
  name: pod-first
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
---
apiVersion: v1
kind: Pod
metadata:
  name: pod-second
  labels:
    app: db
    tier: backend
spec:
  containers:
  - name: busybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command: ["sh", "-c", "sleep 3600"]
  affinity:
    # Pod 亲和性
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          # 这里需要注意冒号后面要有空格
          matchExpressions:
          - {key: app, operator: In, values: ["myapp"]}
        # 位置标识,这是一个标签,可以通过自定义标签配置位置  
        topologyKey: kubernetes.io/hostname

不出意外,这两个Pod会运行在同一个节点上,因为topologyKey使用的是kubernetes.io/hostname标签,它会将两个Pod调度到值相同的节点上

所以,如果想让Pod运行在不同机器但是同一机房或者机柜,只需要预先定义标签,topologyKey选择对应标签即可。

反亲和性调度

反亲和性调度和亲和性调度一样,关键都在于topologyKey,只不过作用是相反的

这里我给两个节点都打了一个相同的标签idc=nj

# kubectl label node node002 idc=nj
# kubectl label node node003 idc=nj

然后根据idc这个标签作为topologyKey,意图实现假如pod-first调度到了南京idc,pod-second就要调度到其他idc,但是这里没有其他节点,所以pod-second状态应该是无法调度的

apiVersion: v1
kind: Pod
metadata:
  name: pod-first
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
---
apiVersion: v1
kind: Pod
metadata:
  name: pod-second
  labels:
    app: db
    tier: backend
spec:
  containers:
  - name: busybox
    image: busybox:latest
    imagePullPolicy: IfNotPresent
    command: ["sh", "-c", "sleep 3600"]
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - {key: app, operator: In, values: ["myapp"]}
        topologyKey: idc

查看创建情况

# kubectl get pods -o wide
pod-first                1/1       Running             0          11s       10.244.2.28   node003
pod-second               0/1       Pending             0          11s       <none>        <none>

查看pod-second调度情况,确实由于没有其他idc值,所以pod-second调度无法成功

Events:
  Type     Reason            Age                From               Message
  ----     ------            ----               ----               -------
  Warning  FailedScheduling  1s (x12 over 34s)  default-scheduler  0/3 nodes are available: 1 node(s) had taints that the pod didn't tolerate, 2 node(s) didn't match pod affinity/anti-affinity, 2 node(s) didn't match pod anti-affinity rules.

results matching ""

    No results matching ""