## Intro

Kubernetes Node Affinity is a powerful scheduling feature that lets you control which nodes your pods can be placed on based on node labels. It is essential for scenarios such as ensuring workloads run on nodes with specific hardware (GPU, SSD), dedicated nodes for certain teams, or colocating services with data locality. However, experimenting with Node Affinity directly in a production cluster can be risky: misconfigured affinity rules may cause pods to become unschedulable, affecting service availability.

A local lab environment provides a safe, isolated space to learn and test Node Affinity rules before applying them to production. In this guide, we will set up a local Kubernetes cluster and walk through practical examples of Node Affinity, including required and preferred rules, verification, and rollback. By the end, you will have a repeatable lab workflow to develop and validate affinity configurations confidently.

This guide is for developers, DevOps engineers, and technical startup teams who want hands-on experience with Node Affinity without endangering live systems.

## Version and Environment Inventory

Before starting, establish a consistent local environment. We will use the following versions and tools, but you can adapt to your available setup. Table 1 summarizes the components.

| Component | Description | Version/Notes |
|---|---|---|
| Kubernetes cluster | Local single-node cluster for testing | v1.27 or later (using kind or minikube) |
| kubectl | CLI for interacting with the cluster | v1.27 or later |
| Container runtime | For local cluster nodes | Docker (for kind) or minikube's driver |
| Node labels | Used to demonstrate affinity | Custom labels like `disktype=ssd` and `gpu=true` |
| Test namespaces | Isolation for experiments | `affinity-test` |

We recommend using a tool like kind (Kubernetes in Docker) or minikube to create a local cluster. Both are well-maintained and easy to set up. For this guide, we will use kind because it allows creating multi-node clusters quickly, which is useful to demonstrate affinity across nodes.

### Prerequisites

- Docker installed and running (for kind).
- kubectl installed and configured to point to the local cluster.
- Basic familiarity with Kubernetes concepts (pods, nodes, labels, scheduling).
- Sufficient local resources: at least 4GB RAM and 2 CPUs recommended.

### Setting up the local cluster

Create a multi-node cluster with kind. Save the following configuration as `kind-config.yaml` to define one control-plane node and two worker nodes. Multi-worker nodes are needed to observe scheduling differences.

```yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker
```

Create the cluster:

```bash
kind create cluster --name node-affinity-lab --config kind-config.yaml
```

Expected output:

```
Creating cluster "node-affinity-lab" ...
 ✓ Ensuring node image (kindest/node: v1.27.3) 🖼
 ✓ Preparing nodes 📦 📦 📦
 ✓ Writing configuration 📜
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Installing StorageClass 💾
 ✓ Joining worker nodes 🚜
Set kubectl context to "kind-node-affinity-lab"
You can now use your cluster with:

kubectl cluster-info --context kind-node-affinity-lab
```

Verify the nodes are ready:

```bash
kubectl get nodes
```

Output:

```
NAME                                 STATUS   ROLES           AGE   VERSION
node-affinity-lab-control-plane      Ready    control-plane   1m    v1.27.3
node-affinity-lab-worker             Ready    <none>          1m    v1.27.3
node-affinity-lab-worker2            Ready    <none>          1m    v1.27.3
```

Now you have a safe local cluster ready for experimenting with Node Affinity.

## Safe Configuration Path

In this section, we will configure Node Affinity in a controlled, scoped manner to minimize impact.

### Understanding Node Affinity

Node Affinity is specified in the pod spec under `spec.affinity.nodeAffinity`. It comes in two flavors:

- **requiredDuringSchedulingIgnoredDuringExecution**: Hard requirement. The scheduler will only place the pod on nodes that satisfy the rule. If no node matches, the pod remains unscheduled.
- **preferredDuringSchedulingIgnoredDuringExecution**: Soft preference. The scheduler tries to place the pod on nodes that match, but if none are available, it will place it elsewhere.

Additionally, node selectors (`nodeSelector`) are a simpler but less expressive alternative. Node Affinity offers more flexibility, including operators like `In`, `NotIn`, `Exists`, `Gt`, `Lt`, and multiple match expressions.

### Labeling nodes for testing

First, add custom labels to the worker nodes to differentiate them.

```bash
# Label worker node with disktype=ssd
kubectl label node node-affinity-lab-worker disktype=ssd

# Label worker2 with disktype=hdd and gpu=true
kubectl label node node-affinity-lab-worker2 disktype=hdd
gpu=true
```

Verify labels:

```bash
kubectl get nodes --show-labels
```

Output snippet:

```
node-affinity-lab-worker    Ready    <none>   1m   v1.27.3   disktype=ssd,...
node-affinity-lab-worker2   Ready    <none>   1m   v1.27.3   disktype=hdd,gpu=true,...
```

### Creating a test namespace

To keep experiments isolated, create a dedicated namespace:

```bash
kubectl create namespace affinity-test
```

### Example 1: Required Node Affinity with In operator

Create a pod that must be scheduled on a node with `disktype=ssd`. Save as `required-affinity.yaml`:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-required-ssd
  namespace: affinity-test
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80
```

Apply the pod:

```bash
kubectl apply -f required-affinity.yaml -n affinity-test
```

Check pod scheduling:

```bash
kubectl get pods -n affinity-test -o wide
```

Expected output shows the pod scheduled on `node-affinity-lab-worker` (which has `disktype=ssd`):

```
NAME                 READY   STATUS    RESTARTS   AGE   IP           NODE                     NOMINATED NODE   READINESS GATES
nginx-required-ssd   1/1     Running   0          10s   10.244.1.2   node-affinity-lab-worker   <none>           <none>
```

### Example 2: Required Node Affinity with mismatch (unschedulable)

Now create a pod that requires `disktype=nvme`, which no node has. Save as `required-nvme.yaml`:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-required-nvme
  namespace: affinity-test
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: disktype
            operator: In
            values:
            - nvme
  containers:
  - name: nginx
    image: nginx:latest
```

Apply and check status:

```bash
kubectl apply -f required-nvme.yaml -n affinity-test
kubectl get pods -n affinity-test
```

The pod will remain in `Pending` state because no node satisfies the affinity. Describe the pod to see the reason:

```bash
kubectl describe pod nginx-required-nvme -n affinity-test
```

Output snippet:

```
Events:
  Type     Reason            Age   From               Message
  ----     ------            ----  ----               -------
  Warning  FailedScheduling  2m    default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.
```

This demonstrates the hard requirement behavior. Clean up the unschedulable pod to avoid clutter:

```bash
kubectl delete pod nginx-required-nvme -n affinity-test
```

### Example 3: Preferred Node Affinity

Use `preferredDuringSchedulingIgnoredDuringExecution` to express a preference. Save as `preferred-affinity.yaml`:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-preferred-ssd
  namespace: affinity-test
spec:
  affinity:
    nodeAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        preference:
          matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd
  containers:
  - name: nginx
    image: nginx:latest
```

Apply and inspect:

```bash
kubectl apply -f preferred-affinity.yaml -n affinity-test
kubectl get pods -n affinity-test -o wide
```

Since a node with `disktype=ssd` exists, the pod will be scheduled there (the preferred node). However, if no such node existed, it would still be scheduled on any available node, unlike the required example.

### Example 4: Combining node affinity and node anti-affinity (optional)

You can also use `NotIn` to avoid certain nodes. For instance, to schedule only on nodes without `gpu=true`:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-no-gpu
  namespace: affinity-test
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: gpu
            operator: DoesNotExist
  containers:
  - name: nginx
    image: nginx:latest
```

This will schedule on a node that does not have the `gpu` label. In our cluster, worker2 has `gpu=true`, so the pod will go to the control-plane or worker (if they lack the label).

## Verification and Diagnostics

After applying affinity rules, you need to verify that scheduling behaves as expected and diagnose any issues.

### Checking pod placement

Use `kubectl get pods -o wide` to see which node a pod is assigned to. For example:

```bash
kubectl get pods -n affinity-test -o wide
```

Output:

```
NAME                 READY   STATUS    RESTARTS   AGE   IP           NODE                     NOMINATED NODE   READINESS GATES
nginx-required-ssd   1/1     Running   0          5m    10.244.1.2   node-affinity-lab-worker   <none>           <none>
nginx-preferred-ssd  1/1     Running   0          1m    10.244.1.3   node-affinity-lab-worker   <none>           <none>
```

### Inspecting node labels

Verify that the labels you expect are present:

```bash
kubectl get node node-affinity-lab-worker --show-labels
```

### Diagnosing unschedulable pods

For pods stuck in `Pending`, use `kubectl describe pod` to view scheduling events. The `FailedScheduling` event will indicate the number of nodes that didn't match and why.

Example:

```bash
kubectl describe pod nginx-required-nvme -n affinity-test
```

Look for lines like:

```
Warning  FailedScheduling  10s   default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.
```

You can also inspect the scheduler logs if needed, but in a local cluster the events are usually sufficient.

### Using kubectl explain

To understand the fields available for node affinity, use:

```bash
kubectl explain pod.spec.affinity.nodeAffinity
```

This prints documentation directly from the API and is helpful for checking syntax.

### Dry-run and validation

Before applying a manifest, validate it with `--dry-run=client`:

```bash
kubectl apply -f required-affinity.yaml --dry-run=client -n affinity-test
```

This will parse the YAML and report any errors without actually creating the resource.

## Failure Modes and Recovery

Even in a lab, things can go wrong. This section covers common failure modes and how to recover.

### Pod stuck in Pending due to unsatisfiable affinity

If a pod has a required affinity that no node satisfies, it will remain pending indefinitely. To recover, either:

- Modify the pod spec to remove or relax the affinity, then reapply.
- Delete the pod if it is no longer needed.

Example:

```bash
kubectl delete pod nginx-required-nvme -n affinity-test
```

### Incorrect label values or typo in key

Ensure labels match exactly. Use `kubectl get nodes --show-labels` to confirm. If a label is missing, add it:

```bash
kubectl label node node-affinity-lab-worker disktype=ssd --overwrite
```

### Accidentally labeling nodes and affecting other workloads

In a shared cluster, labeling nodes can unintentionally influence existing workloads if those workloads use node selectors or affinity. In this lab, we used a dedicated cluster and namespace, but if you share a cluster, consider using unique label keys (e.g., `lab.example.com/disktype`) to avoid collisions.

### Rollback: removing affinity from a deployment

If you applied affinity as part of a Deployment and need to roll back, you can edit the deployment or use `kubectl rollout undo` if the change was part of a revision. For example, to remove node affinity from a deployment:

```bash
kubectl edit deployment myapp -n affinity-test
```

Then remove the affinity section and save. This triggers a rolling update.

### Deleting the entire lab

When you are done, you can delete the namespace and the kind cluster to free resources:

```bash
kubectl delete namespace affinity-test
kind delete cluster --name node-affinity-lab
```

## Common Pitfalls and How to Avoid Them

Node Affinity is straightforward but has nuances that can trip you up. Here are the most common pitfalls and how to avoid them.

### 1. Forgetting that labels are case-sensitive and exact

**Why it happens:** You write `disktype=SSD` in the affinity but the node has `disktype=ssd`. The scheduler treats them as different strings, so the pod will not schedule.

**How to avoid:** Always copy label keys and values exactly from `kubectl get nodes --show-labels`. Use lowercase and consistent naming conventions.

**Recovery:** If a pod is pending, describe it to see the mismatch, then correct the manifest or relabel the node.

### 2. Using requiredDuringSchedulingIgnoredDuringExecution when you mean preferred

**Why it happens:** You want to express a preference but mistakenly use required, causing pods to become unschedulable if the condition is not met.

**How to avoid:** Understand the difference: required is a hard constraint, preferred is a soft hint. Use required only when the pod truly cannot run elsewhere.

**Recovery:** Change the field to `preferredDuringSchedulingIgnoredDuringExecution` in the manifest and reapply.

### 3. Not considering node taints and tolerations

**Why it happens:** You set up node affinity to schedule on a specific node, but that node also has a taint that repels pods without a matching toleration. The pod remains pending even though affinity matches.

**How to avoid:** Check node taints with `kubectl describe node <node-name> | grep Taints`. If taints are present, add tolerations to the pod spec.

**Recovery:** Add a toleration for the taint to the pod manifest or remove the taint from the node (if appropriate).

### 4. Overusing node anti-affinity with DoesNotExist

**Why it happens:** Using `operator: DoesNotExist` on a label key that exists on most nodes can unintentionally exclude almost all nodes, leaving no schedulable nodes.

**How to avoid:** Test with `kubectl get nodes --show-labels` to see which nodes have the label. Consider using `NotIn` with specific values instead of `DoesNotExist` if you only want to exclude certain nodes.

**Recovery:** Adjust the operator or values, then reapply.

### 5. Changing node labels after pods are scheduled

**Why it happens:** You change labels on a node, expecting running pods to be evicted. But `IgnoredDuringExecution` means the affinity is only evaluated at scheduling time. Running pods stay put.

**How to avoid:** Understand that Node Affinity (both required and preferred) does not evict running pods when labels change. Use taints or other mechanisms if you need to evict.

**Recovery:** If you need pods to move, delete them so they reschedule, or use a tool like Descheduler.

## Operations Checklist

Use this checklist each time you run a Node Affinity experiment to ensure a smooth workflow. Assign a single owner for each step and schedule a review if needed.

| Step | Action | Verification | Owner | Review Frequency |
|---|---|---|---|---|
| 1 | Ensure local cluster is running | `kubectl get nodes` shows Ready nodes | You (lab user) | Every session |
| 2 | Confirm kubectl context is set to local cluster | `kubectl config current-context` returns `kind-node-affinity-lab` | You (lab user) | Every session |
| 3 | Label nodes with intended test labels | `kubectl get nodes --show-labels` shows labels | You (lab user) | Every session |
| 4 | Create a dedicated namespace for experiment | `kubectl get namespace affinity-test` exists | You (lab user) | Every session |
| 5 | Apply a pod or deployment with affinity | `kubectl apply -f manifest.yaml` succeeds | You (lab user) | Every session |
| 6 | Verify pod scheduling location | `kubectl get pods -o wide` shows correct node | You (lab user) | Every session |
| 7 | For required affinity, test both matching and non-matching cases | Pending pod for non-matching | You (lab user) | Every session |
| 8 | Test preferred affinity fallback | Pod still schedules when no match | You (lab user) | Every session |
| 9 | Document observations and label combinations | Notes saved | You (lab user) | After each experiment |
| 10 | Clean up test resources | Delete pods, namespace, or cluster as needed | You (lab user) | After each experiment |

## Conclusion

Setting up a local Kubernetes Node Affinity lab is a valuable investment for any team that wants to understand and safely leverage scheduling controls. In this guide, we covered environment setup with kind, labeling nodes, creating pods with required and preferred affinity, verifying placement, and recovering from common issues. By following the safe configuration path and using the operations checklist, you can experiment extensively without risk to production.

Next steps:

- Explore more complex affinity rules, such as combining multiple match expressions.
- Experiment with Pod Affinity and Anti-Affinity to control pod co-location.
- Integrate Node Affinity with taints and tolerations for dedicated nodes.
- Test how changes to node labels affect running pods (note that currently running pods are not evicted due to label changes, but new scheduling decisions will reflect them).

With this lab, you are well-equipped to design and validate Node Affinity policies for your production clusters.