daemonset只运行在指定节点

发布时间 2023-08-20 22:19:34作者: 坚强的小蚂蚁

1.spec.template.spec.nodeSelector

如,只在node标签有 daemonset=true 的节点上运行pod:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: ssd-monitor-nodelabel
  namespace: controller-test
spec:
  selector:
    matchLabels:
      app: ssd-monitor-nodelabel
  template:
    metadata:
      labels:
        app: ssd-monitor-nodelabel
    spec:
      nodeSelector:
        daemonset: "true"         # 有一些特殊的需要加""
      containers:
      - name: main
        image: luksa/ssd-monitor

2.spec.template.spec.affinity

https://blog.csdn.net/kozazyh/article/details/112004365

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-hello-deployment
  namespace: chenqiang-ns1
  labels:
    app: nginx-hello
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-hello
  template:
    metadata:
      labels:
        app: nginx-hello
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: tester
                operator: NotIn
                values:
                - chenqiang
      containers:
      - name: nginx-hello
        image: docker-registry.saicstack.com/chenqiang/nginx-hello:v2.0
        ports:
        - containerPort: 80
      imagePullSecrets:
      - name: regcred

pod中的例子

apiVersion: v1
kind: Pod
metadata:
  name: with-node-affinity
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/e2e-az-name
            operator: In
            values:
            - e2e-az1
            - e2e-az2
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 1
        preference:
          matchExpressions:
          - key: another-node-label-key
            operator: In
            values:
            - another-node-label-value
  containers:
  - name: with-node-affinity
    image: gcr.io/google_containers/pause:2.0

这条规则表示,pod可以被调度到标签key为“kubernetes.io/e2e-az-name”,值为“e2e-az1”或“e2e-az2”的节点。另外,在满足该条件的节点中,优先使用具有“another-node-label-key”标签,且至为“another-node-label-value”的节点。
这个 pod 同时定义了 requiredDuringSchedulingIgnoredDuringExecution 和 preferredDuringSchedulingIgnoredDuringExecution 两种 nodeAffinity。第一个要求 pod 运行在特定 AZ 的节点上,第二个希望节点最好有对应的 another-node-label-key:another-node-label-value 标签。

这里的匹配逻辑是label在某个列表中,可选的操作符有:

In: label的值在某个列表中
NotIn:label的值不在某个列表中
Exists:某个label存在
DoesNotExist:某个label不存在
Gt:label的值大于某个值(字符串比较)
Lt:label的值小于某个值(字符串比较)
如果nodeAffinity中nodeSelector有多个选项,节点满足任何一个条件即可;如果matchExpressions有多个选项,则节点必须同时满足这些选项才能运行pod 。

需要说明的是,node并没有anti-affinity这种东西,因为NotIn和DoesNotExist能提供类似的功能。