Node Affinity, Node Selector, and Other Ways to Better Control Kubernetes Scheduling
Tags: kubernetes, cloud, devops
Published: 2023-05-26 08:14:37

<!-- wp:paragraph -->
<p>Assigning pods to nodes is one of the most critical tasks of Kubernetes cluster management. While the default process can prove too generic, you can adjust it with advanced features like <strong>node affinity</strong>.&nbsp;&nbsp;&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The way the Kubernetes scheduler distributes pods across worker nodes impacts performance and resources and, therefore, your costs. It's then essential to understand how the process works and how to keep it in check.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This article outlines basic Kubernetes scheduling concepts, including node selector, node affinity and anti-affinity, and pod affinity and anti-affinity. It also includes an example of how combining node affinity and automation can improve your workload's availability and fault tolerance.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"anchor":"h-how-kubernetes-scheduling-works"} -->
<h2 class="wp-block-heading" id="h-how-kubernetes-scheduling-works">How Kubernetes scheduling works</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Kubernetes scheduling is about selecting a suitable node to run pods. <em>Kube-scheduler</em> is part of the control plane and it selects nodes for new or not yet scheduled pods, by default trying to spread them evenly.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Containers in pods can have different requirements, so the Kubernetes scheduler filters out any nodes that don't match the pod's specific needs.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The Kubernetes scheduler identifies and scores all feasible nodes for your pod. It then picks the one with the highest score and notifies the API server about this decision.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":19584,"width":696,"height":700,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image aligncenter size-full is-resized"><img src="https://cast.ai/wp-content/uploads/2023/04/des-397-new-stack-1.png" alt="Node affinity, node selector and other ways to better control Kubernetes scheduling" class="wp-image-19584" width="696" height="700"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Several factors impact the scheduler's decisions, such as resource requirements, hardware and software constraints, etc.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The Kubernetes scheduler is fast, thanks to automation. However, it can be expensive as you may have to pay for resources that are insufficient for your different environments.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And as there's no easy way to track your costs in Kubernetes, teams must find other ways to keep their expenses in check.&nbsp;&nbsp;&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"anchor":"how-to-control-the-scheduler-s-choices"} -->
<h2 class="wp-block-heading" id="how-to-control-the-scheduler-s-choices">How to control the scheduler’s choices&nbsp;</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In a nutshell, you can control where your pods go with <a href="https://cast.ai/blog/kubernetes-labels-expert-guide-with-10-best-practices/">Kubernetes labels</a>.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Labels are key/value pairs you can manually attach to objects like pods and nodes. By using them, you can specify identifying attributes, organize, or select subsets of objects.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The simplest way to constrain the Kubernetes scheduler is to use a node selector.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3,"anchor":"how-does-a-node-selector-work"} -->
<h3 class="wp-block-heading" id="how-does-a-node-selector-work">How does a node selector work?&nbsp;</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Adding the node selector field to your pod specification with a key-value pair lets you indicate the labels you wish the target node to have.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Kubernetes will only schedule pods onto the nodes matching the labels you specify.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>The node selector is sufficient in small clusters but is usually unsuitable for complex cases.&nbsp;</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, you may have an app that needs to run in separate availability zones. Or you may want to keep the API and database separate, e.g., when you don’t have many replicas.&nbsp;&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That’s where the concept of affinity comes in handy. &nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3,"anchor":"moving-beyond-the-node-selector-with-affinity"} -->
<h3 class="wp-block-heading" id="moving-beyond-the-node-selector-with-affinity">Moving beyond the node selector with affinity</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Affinity and anti-affinity expand the types of constraints you can add and give you more control over the selection logic.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Using them, you can create "preferred" and "soft" rules for different conditions for Kubernetes to schedule the pod even if there are no perfectly matching nodes. They also let you match the labels of pods running on the same nodes and specify the location of new pods more precisely.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>It’s essential to keep in mind that there are two types of affinity:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li><strong>Node affinity</strong> refers to impacting how pods get matched to nodes.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li><strong>Pod affinity</strong> specifies how pods can be scheduled based on the labels of pods already running on that node.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Let’s now discuss both of them to highlight the difference.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"anchor":"node-affinity-what-is-it-and-how-does-it-work"} -->
<h2 class="wp-block-heading" id="node-affinity-what-is-it-and-how-does-it-work">Node affinity: what is it, and how does it work?&nbsp;</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Similar to node selector, node affinity also lets you use labels to specify to which nodes Kube-scheduler should schedule your pods.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can specify it by adding the <em>.spec.affinity.nodeAffinity</em> field in your pod.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Remember that if you specify <em>nodeSelector</em> and <em>nodeAffinity</em>, both must be met for the pod to be scheduled.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>There are two types of node affinity:&nbsp;&nbsp;&nbsp;</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li><strong>requiredDuringSchedulingIgnoredDuringExecution</strong> – when using this one, the scheduler will only schedule the pod if the node meets the rule.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li><strong>preferredDuringSchedulingIgnoredDuringExecution</strong>– in this scenario, the scheduler will try to find a node matching the rule, but it will still schedule the pod even if it doesn't find anything suitable.&nbsp;</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>The latter lets you specify each instance’s weight by using a value between 1 and 100.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When the scheduler finds nodes meeting all of your unscheduled pod’s requirements, Kube-scheduler iterates through every preferred rule that the node matches and adds the value of the weight to a sum.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The Kubernetes scheduler then adds this sum to the final score, impacting your pod's final node decision.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"anchor":"what-is-pod-affinity"} -->
<h2 class="wp-block-heading" id="what-is-pod-affinity">What is pod affinity?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Working along similar lines, this concept focuses on impacting the Kubernetes scheduler based on the labels on the pods already running on a given node.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can also specify it within the affinity section using the podAffinity and podAntiAffinity fields in the pod spec.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li><strong>Pod affinity</strong> assumes that a given pod can run in a specific location if there is already a pod meeting particular conditions.&nbsp;</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li><strong>Pod anti-affinity </strong>offers the opposite functionality, preventing pods from running on the same node as pods matching particular criteria.&nbsp;</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>There is a separate post diving into <a href="https://cast.ai/blog/kubernetes-scheduler-how-to-make-it-work-with-inter-pod-affinity-and-anti-affinity/">inter-pod affinity and anti-affinity.</a>&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That’s why, for now, let’s focus on one practical application of node affinity.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"anchor":"node-affinity-in-action-high-availability-and-fault-tolerance"} -->
<h2 class="wp-block-heading" id="node-affinity-in-action-high-availability-and-fault-tolerance">Node affinity in action: high availability and fault tolerance</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Availability is the holy grail of migrating to the cloud, and you can also boost it with node affinity.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>By spreading pods across several different nodes, you can ensure that your application remains available even if one or more of those nodes fail.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>With node affinity, you can instruct the Kubernetes scheduler to choose nodes in different availability zones, data centers, or regions. By doing so, your app can continue running even if your AZ or data center experiences an outage.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you then add <a href="https://cast.ai/">Kubernetes automation</a>, you can ensure that pods get scheduled in the preferred zones even if they’re not present in your cluster.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Here is an example deployment of an on-demand instance on AWS with affinity set for a single zone:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-cross-single-az
  labels:
    app: nginx-cross-single-az
spec:
  replicas: 5
  selector:
    matchLabels:
      app: nginx-single-az
  template:
    metadata:
      labels:
        app: nginx-single-az
    spec:
      nodeSelector:
        topology.kubernetes.io/zone: "eu-central-1a"
      containers:
      - name: nginx
        image: nginx:1.24.0
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 2</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In this case, the node selector will pick nodes with the label "<strong>topology.kubernetes.io/zone</strong>" set to "<strong>eu-central-1a</strong>".&nbsp;&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>For comparison, here’s an example of node affinity set for multi-zone pod scheduling:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-cross-az
  labels:
    app: nginx-cross-az
spec:
  replicas: 5
  selector:
    matchLabels:
      app: nginx-cross-az
  template:
    metadata:
      labels:
        app: nginx-cross-az
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: "topology.kubernetes.io/zone"
                operator: In
                values:
                - eu-central-1a
                - eu-central-1b
                - eu-central-1c
      containers:
      - name: nginx
        image: nginx:1.24.0
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 2</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In this scenario, CAST AI will create nodes across multiple AWS zones that match your requirements. It will use on-demand instances, and all provisioning will happen automatically.&nbsp;&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"anchor":"summary"} -->
<h2 class="wp-block-heading" id="summary">Summary</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Kubernetes affinity is an important feature allowing you to control your pod scheduling better.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Pod and node affinity and anti-affinity let you have more say on where your pods get scheduled. By specifying these rules, you get more scheduling configurations.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Add automation to ensure that your pods get distributed across the most suitable nodes at all times and easily keep a tab on all related costs.&nbsp;</p>
<!-- /wp:paragraph -->