Kubernetes - deep dive questions - Series 02 - Solution

Kubernetes - deep dive questions - Series 02 - Solution

  1. Question Area : Node Affinity:

    • Describe what node affinity is and provide a scenario where you'd need to use it. Show a YAML configuration snippet demonstrating how to set a pod's affinity to nodes labeled with zone=west.

Solutions : Node affinity is conceptually similar to nodeSelector, allowing you to constrain which nodes your Pod can be scheduled on based on node labels. There are two types of node affinity:

requiredDuringSchedulingIgnoredDuringExecution: The scheduler can't schedule the Pod unless the rule is met. This functions like nodeSelector, but with a more expressive syntax.

preferredDuringSchedulingIgnoredDuringExecution: The scheduler tries to find a node that meets the rule. If a matching node is not available, the scheduler still schedules the Pod.

apiVersion: v1
kind: Pod
metadata:
  name: with-node-affinity
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: zone
            operator: In
            values:
            - west
      preferredDuringSchedulingIgnoredDuringExecution: #Another Option 
      - weight: 1
        preference:
          matchExpressions:
          - key: another-node-label-key
            operator: In
            values:
            - another-node-label-value
  containers:
  - name: with-node-affinity
    image: registry.k8s.io/pause:2.0

Explanation :

Spec (Specification):

  • Affinity:

    • Node Affinity:

      • Required During Scheduling Ignored During Execution:

        • This section contains rules that must be met for a pod to be scheduled on a node.

        • nodeSelectorTerms: A list of node selector terms, where each term specifies a set of conditions that a node must meet.

          • Match Expressions:

            • A key-value pair used for selecting nodes.

            • key: topology.kubernetes.io/zone

            • operator: In (this means the key's value must be in the set of values provided)

            • values: Specifies the values for the key. In this case, the values are antarctica-east1 and antarctica-west1. The pod can only be scheduled on nodes with these zone labels.

      • Preferred During Scheduling Ignored During Execution:

        • This section contains preferences that the scheduler will try to enforce but will not guarantee.

        • weight: Assigned as 1 (weights can be between 0 and 100).

        • preference: Defines a node preference.

          • Match Expressions:

            • key: another-node-label-key

            • operator: In

            • values: Contains a single value another-node-label-value. The scheduler will prefer nodes with this label.