Kubernetes - Node Selectors and Affinity đ
Description đ
You have different types of workloads running on your cluster, and you want to make sure that the right workloads are running on the right nodes. For example, you might want to run a set of pods on a high CPU node, and run another set of pods on a low CPU node. You can use node selectors to make sure that the right pods are running on the right nodes.
-
Node Selectors
Node selectors are constrained to
nodelabels.Nodelabelsarekey-valuepairs that are attached tonodes.Nodelabelscan be used innodeselectorsspecified inpoddefinitions.Nodeselectorswork by matchingnodelabelswithpodlabels. Apodcan only be scheduled onto anodeif thenodelabelsmatch thepodlabels. -
Node Affinity
Instead you can use
Node Affinityto perform the same task.Node Affinityis a field inpoddefinitions. It specifies a set ofrulesthat are used to matchnodeswithpods.Node Affinitycan be used in conjunction withnodeselectors.Node Affinitycan also be used to specify apreferrednodethat should be used to run apod.Node Affinityis more expressive thannodeselectors.Node Affinitycan specify weight for eachrule.Node Affinitycan specify whether or not aruleis required.Node Affinitycan specify howmanyrulesmust be satisfied for thepodto be scheduled onto anode.
Basic Commands đ
-
to label a
nodekubectl label nodes <node-name> <label-key>=<label-value>
Examples đ§Š
-
sample
poddefinition withnodeselectorapiVersion: v1 kind: Pod metadata: name: my-app spec: containers: - name: nginx image: nginx nodeSelector: size: Large -
sample
poddefinition withnodeaffinityapiVersion: v1 kind: Pod metadata: name: my-app spec: containers: - name: nginx image: nginx affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: size operator: In values: - Large
Red and Blue Example đ´đĻ
-
red
deploymentdefinition đ´apiVersion: apps/v1 kind: Deployment metadata: name: red spec: replicas: 2 selector: matchLabels: app: red template: metadata: name: red labels: app: red spec: containers: - image: nginx name: nginx affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: color operator: In values: - red -
blue
deploymentdefinition đĻapiVersion: apps/v1 kind: Deployment metadata: name: blue spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: name: blue labels: type: pod app: nginx spec: containers: - name: nginx image: nginx affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: color operator: In values: - blue