简介

nodeAffinity就是节点亲和性,相对应的是Anti-Affinity,就是反亲和性。

这种方法比nodeSelector灵活,可以有一些简单的逻辑组合。

调度可以分成软策略和硬策略两种方式:

  • 软策略就是如果你没有满足调度要求的节点的话,POD 就会忽略这条规则,继续完成调度过程。
  • 没有满足条件的节点的话,就不断重试直到满足条件为止。

例子

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: hostname
  name: hostname
  namespace: default
spec:
  progressDeadlineSeconds: 600
  replicas: 2
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: hostname
  strategy:
    rollingUpdate:
      maxSurge: 10%
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: hostname
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/hostname
                operator: In
                values:
                - k8s-node.example.com
                - centos7.example.com
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            preference:
              matchExpressions:
              - key: node-type
                operator: In
                values:
                - testing
      containers:
      - image: tosomeone/hostname:v1.0.3
        imagePullPolicy: IfNotPresent
        resources:
          requests:
            memory: 20Mi
            cpu: 100m
          limits:
            memory: 30Mi
            cpu: 150m
        livenessProbe:
          failureThreshold: 5
          httpGet:
            path: /
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 1
          periodSeconds: 2
          successThreshold: 1
          timeoutSeconds: 2
        name: hostname
        ports:
        - containerPort: 8080
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 2
          periodSeconds: 1
          successThreshold: 1
          timeoutSeconds: 5
        lifecycle:
          postStart:
            exec:
              command:
                - echo
                - "started"
          preStop:
            exec:
              command:
                - sleep
                - "3"
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30

preferredDuringSchedulingIgnoredDuringExecution:指定的就是软策略

requiredDuringSchedulingIgnoredDuringExecution:指定的就是硬策略

例子中优先选择node上有node-type=testing标签的node,且这些node需要满足主机名k8s-node.example.com或者centos7.example.com

操作符有下面的几种:

  • In:label 的值在某个列表中
  • NotIn:label 的值不在某个列表中
  • Gt:label 的值大于某个值
  • Lt:label 的值小于某个值
  • Exists:某个 label 存在
  • DoesNotExist:某个 label 不存在