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
node
labels
.Node
labels
arekey-value
pairs that are attached tonodes
.Node
labels
can be used innode
selectors
specified inpod
definitions.Node
selectors
work by matchingnode
labels
withpod
labels
. Apod
can only be scheduled onto anode
if thenode
labels
match thepod
labels
. -
Node Affinity
Instead you can use
Node Affinity
to perform the same task.Node Affinity
is a field inpod
definitions. It specifies a set ofrules
that are used to matchnodes
withpods
.Node Affinity
can be used in conjunction withnode
selectors
.Node Affinity
can also be used to specify apreferred
node
that should be used to run apod
.Node Affinity
is more expressive thannode
selectors
.Node Affinity
can specify weight for eachrule
.Node Affinity
can specify whether or not arule
is required.Node Affinity
can specify howmany
rules
must be satisfied for thepod
to be scheduled onto anode
.
Basic Commands
đ
-
to label a
node
kubectl label nodes <node-name> <label-key>=<label-value>
Examples đ§Š
-
sample
pod
definition withnode
selector
apiVersion: v1 kind: Pod metadata: name: my-app spec: containers: - name: nginx image: nginx nodeSelector: size: Large
-
sample
pod
definition withnode
affinity
apiVersion: 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
deployment
definition đ´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
deployment
definition đĻ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