标签(labels)是Kubernetes中一个重要的概念。Service、Deployment和Pod都是通过labels实现关联。而在节点上,您也可以通过设置标签相关的策略使得Pod调度到对应标签的节点上。本文介绍如何调度应用到指定的节点池。

操作步骤

  1. 给节点池设置节点标签。
    您可以在ACK中通过节点池管理集群中的一组节点资源。例如在节点池中统一管理节点的标签和污点。有关创建节点池的具体步骤,请参见创建节点池
    1. 登录容器服务管理控制台
    2. 在控制台左侧导航栏,单击集群
    3. 集群列表页面中,单击目标集群右侧操作列下的节点池
    4. 节点池页面,单击创建节点池
    5. 在创建节点池配置页,单击显示高级选项,然后单击节点标签右侧的节点池设置节点标签。
      本文示例中添加的节点标签为pod: nginx。
    您也可以在目标节点池右侧操作列下单击扩容为节点更新或者添加标签。对于已开启自动伸缩的节点池,单击目标节点池右侧操作列下的修改为节点更新或者添加标签。Podnginx
  2. 为应用设置调度策略。
    上述步骤已经为节点池中的节点设置了pod:nginx的标签。您可以利用nodeSelector或者nodeAffinity保证您的应用限定在指定节点池上运行。具体操作步骤如下。
    • 设置nodeSelector
      nodeSelector是Podspec中一个字段。您只需要将上述的pod: nginx标签填充到nodeSelector中。示例如下。
      apiVersion: apps/v1 
      kind: Deployment
      metadata:
        name: nginx-deployment-basic
        labels:
          app: nginx
      spec:
        replicas: 2
        selector:
          matchLabels:
            app: nginx
        template:
          metadata:
            labels:
              app: nginx
          spec:
            nodeSelector:
              pod: nginx      #节点池中的标签添加到这里以保证您的应用只可以运行在节点池的节点上。
            containers:
            - name: nginx
              image: nginx:1.7.9
              ports:
              - containerPort: 80
    • 设置nodeAffinity
      您还可以使用nodeAffinity实现应用的调度需求。nodeAffinity包含以下调度策略:
      • - requiredDuringSchedulingIgnoredDuringExecution

        表示Pod必须部署到满足条件的节点上。如果没有满足条件的节点,调度操作就不停重试。其中IgnoreDuringExecution表示Pod部署之后运行时,如果节点标签发生了变化,不再满足Pod指定的条件,Pod也会继续运行。

      • - preferredDuringSchedulingIgnoredDuringExecution

        表示优先部署到满足条件的节点上,如果没有满足条件的节点,就忽略这些条件,按照正常逻辑部署。

      本文示例使用requiredDuringSchedulingIgnoredDuringExecution策略保证应用一直运行在指定的节点池上。
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: nginx-with-affinity
        labels:
          app: nginx-with-affinity
      spec:
        replicas: 2
        selector:
          matchLabels:
            app: nginx-with-affinity
        template:
          metadata:
            labels:
              app: nginx-with-affinity
          spec:
            affinity:
              nodeAffinity:
                requiredDuringSchedulingIgnoredDuringExecution:
                  nodeSelectorTerms:
                  - matchExpressions:
                    - key: pod
                      operator: In      # 这里就相当于应用将运行在标了pod:nginx的节点上。
                      values:
                      - nginx
            containers:
            - name: nginx-with-affinity
              image: nginx:1.7.9
              ports:
              - containerPort: 80

执行结果

上述部署的应用全部被调度到了xxx.xxx.0.74的节点上,这个节点正是本文示例中在节点池中打了标签(pod: nginx)的节点。label