# Scheduling: where Pods run

How the scheduler picks a node, and how to steer it: node selectors, taints and tolerations, topology spread across zones, and draining a node safely with a PodDisruptionBudget.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 11. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/11-scheduling

## What you will learn

- Explain how the scheduler filters and scores nodes
- Spread Pods across availability zones with topologySpreadConstraints
- Reserve a node with a taint and let only tolerating Pods in
- Drain a node for maintenance and see a PodDisruptionBudget protect an app

> **Lab status.** **Verified lab:** topology spread across two zones, a taint keeping a Pod out, and a drain blocked by a PodDisruptionBudget, on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** node affinity and priority (explained). <br />**Cloud lab:** zone spreading needs a multi-zone cluster; the rest works on kind.

Most of the time you don't care which node a Pod lands on. Sometimes you do: spread replicas so one zone's
outage doesn't take them all, keep special workloads on special nodes, and move Pods off a node safely before
maintenance.

## How the scheduler decides

For every new Pod, the scheduler runs two phases:

1. **Filter**: drop nodes that can't run it: not enough unreserved CPU or memory for its requests, a node
   selector that doesn't match, a taint it doesn't tolerate, a volume in another zone.
2. **Score**: rank the rest, preferring spread-out placement and balanced usage, and pick the best.

> **Figure.** Animated. A new Pod requesting 100m CPU waits, unscheduled. Three nodes from the course cluster: ip-10-42-0-115 in ap-south-1a, ip-10-42-14-248 in ap-south-1a, cordoned and SchedulingDisabled, and ip-10-42-28-149 in ap-south-1b. Step 1, filter: ip-10-42-14-248 is crossed out as unschedulable. Step 2, score: the two remaining nodes get score bars for spread and balanced use; ip-10-42-28-149 scores higher. Step 3, bind: the scheduler writes spec.nodeName and the Pod moves to ip-10-42-28-149, where the kubelet starts it. Scores are illustrative.
>
> The three real nodes from the lab. Filter reasons are real; the score bars are illustrative.

If no node passes the filter, the Pod stays **Pending** and the scheduler writes why in its events, as lessons 9
and 10 showed.

## Spread across zones

The course cluster has nodes in two zones:

```text
$ kubectl get nodes -L topology.kubernetes.io/zone
NAME                                          STATUS                     ROLES    AGE   VERSION               ZONE
ip-10-42-0-115.ap-south-1.compute.internal    Ready                      <none>   63m   v1.37.1-eks-6e7947a   ap-south-1a
ip-10-42-14-248.ap-south-1.compute.internal   Ready,SchedulingDisabled   <none>   12m   v1.37.1-eks-6e7947a   ap-south-1a
ip-10-42-28-149.ap-south-1.compute.internal   Ready                      <none>   63m   v1.37.1-eks-6e7947a   ap-south-1b
```

(The middle node was the Cluster Autoscaler's extra node, already **SchedulingDisabled** because the autoscaler
was removing it.) To guarantee replicas end up in both zones:

```yaml
# 11-spread.yaml (excerpt)
spec:
  replicas: 4
  template:
    spec:
      topologySpreadConstraints:
        - maxSkew: 1 # zones may differ by at most 1 Pod
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: spread
```

```text
$ kubectl get pods -l app=spread -o custom-columns=POD:.metadata.name,NODE:.spec.nodeName
spread-b547844df-52tsg   ip-10-42-0-115.ap-south-1.compute.internal
spread-b547844df-58j5p   ip-10-42-28-149.ap-south-1.compute.internal
spread-b547844df-chwpt   ip-10-42-28-149.ap-south-1.compute.internal
spread-b547844df-pvtb5   ip-10-42-0-115.ap-south-1.compute.internal
```

> **Figure.** Two zones side by side. Zone ap-south-1a has node ip-10-42-0-115 running spread Pods 52tsg and pvtb5, and node ip-10-42-14-248, SchedulingDisabled, running none. Zone ap-south-1b has node ip-10-42-28-149 running spread Pods 58j5p and chwpt. Below: the count is 2 in each zone, skew 0, within maxSkew 1. A Pod that would make it 3 against 1 stays Pending instead. If ap-south-1a fails, 2 of the 4 Pods keep serving.
>
> Where the four spread Pods really landed: two per zone, skew 0.

Two Pods per zone. If ap-south-1a went down, half the app would keep serving. `whenUnsatisfiable: ScheduleAnyway`
makes it a preference instead of a rule.

## Taints and tolerations

A **taint** on a node repels Pods; a **toleration** on a Pod lets it in anyway. Use them to reserve nodes: GPU
machines, nodes for batch jobs, or nodes for one team.

```text
$ kubectl label node ip-10-42-0-115.ap-south-1.compute.internal workload=batch
$ kubectl taint node ip-10-42-0-115.ap-south-1.compute.internal dedicated=batch:NoSchedule
```

Two Pods both select that node with `nodeSelector: workload: batch`; only the first tolerates the taint:

```yaml
# 11-gpu-only.yaml (excerpt, first Pod)
tolerations:
  - key: dedicated
    operator: Equal
    value: batch
    effect: NoSchedule
nodeSelector:
  workload: batch
```

```text
$ kubectl get pods tolerates-dedicated no-toleration -o wide
tolerates-dedicated   1/1     Running   0          19s   10.42.3.48   ip-10-42-0-115.ap-south-1.compute.internal   <none>           <none>
no-toleration         0/1     Pending   0          18s   <none>       <none>                                       <none>           <none>
$ kubectl describe pod no-toleration | sed -n '/Events:/,$p'
  Warning  FailedScheduling   21s   default-scheduler   0/3 nodes are available: 1 node(s) didn't match Pod's node affinity/selector, 1 node(s) had untolerated taint(s), 1 node(s) were unschedulable. ...
```

> **Figure.** Left, two Pods that both select workload=batch. Pod tolerates-dedicated has a toleration for dedicated=batch NoSchedule and goes onto node ip-10-42-0-115: Running, IP 10.42.3.48. Pod no-toleration is pushed back by the taint and stays Pending. Right, the scheduler's message, 0/3 nodes are available, split per node: ip-10-42-28-149 did not match the node selector, ip-10-42-0-115 had an untolerated taint, ip-10-42-14-248 was unschedulable. Bottom, the three taint effects: NoSchedule blocks new Pods, PreferNoSchedule avoids the node if possible, NoExecute also evicts running Pods.
>
> One Pod tolerates the taint and runs; the other is kept out, and the scheduler explains every node.

The scheduler's message accounts for every node: one didn't match the selector, one had the taint, one was being
removed. A toleration only **allows** a Pod onto a tainted node; it doesn't send it there. That's why the example
pairs it with a node selector (or node affinity, its more flexible form). Effects: `NoSchedule` blocks new Pods,
`PreferNoSchedule` avoids if possible, `NoExecute` also evicts Pods already running.

## Draining and evictions

Before upgrading or replacing a node, you **drain** it: mark it unschedulable (cordon) and evict its Pods so
their controllers recreate them elsewhere. A **PodDisruptionBudget** stops a drain from taking too many replicas
of one app at once:

```yaml
# 11-pdb.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: shop-web
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: shop-web
```

At that moment shop-web had exactly 2 replicas:

```text
$ kubectl get pdb shop-web
NAME       MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
shop-web   2               N/A               0                     3s
$ kubectl drain ip-10-42-0-115.ap-south-1.compute.internal --ignore-daemonsets --delete-emptydir-data --timeout=180s
node/ip-10-42-0-115.ap-south-1.compute.internal cordoned
Warning: ignoring DaemonSet-managed Pods: kube-system/aws-node-hqdfw, kube-system/ebs-csi-node-lp977, kube-system/eks-pod-identity-agent-mfk7m, kube-system/kube-proxy-6r4f2
evicting pod default/shop-web-57f494cdcb-ltvkc
error when evicting pods/"shop-web-57f494cdcb-ltvkc" -n "default" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
pod/aws-load-balancer-controller-6f89d47788-5fj68 evicted
pod/coredns-8966fd9f9-b7ppz evicted
pod/metrics-server-596c8d7669-j7hrt evicted
...
error when evicting pods/"shop-web-57f494cdcb-ltvkc" -n "default" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
...
There are pending nodes to be drained:
$ kubectl uncordon ip-10-42-0-115.ap-south-1.compute.internal
node/ip-10-42-0-115.ap-south-1.compute.internal uncordoned
```

> **Figure.** Animated, from the lab. Node ip-10-42-0-115 runs shop-web-57f494cdcb-ltvkc, aws-load-balancer-controller, coredns and metrics-server, plus four DaemonSet Pods: aws-node, ebs-csi-node, eks-pod-identity-agent and kube-proxy. Step 1, cordon: the node becomes SchedulingDisabled. Step 2, evict: the load balancer controller, coredns and metrics-server are evicted and their Deployments recreate them on other nodes. DaemonSet Pods are ignored and stay. Step 3: evicting shop-web is refused again and again, Cannot evict pod as it would violate the pod's disruption budget, because shop-web has 2 replicas, the other one shop-web-57f494cdcb-tckth on ip-10-42-28-149, and minAvailable is 2, so allowed disruptions is 0. Step 4: the drain times out after 180 seconds and the node is uncordoned.
>
> The drain from the lab: three Pods moved, DaemonSets stayed, and the PDB refused the last eviction until the timeout.

Everything else moved off the node, but the shop-web Pod didn't: with 2 replicas and `minAvailable: 2`, **allowed
disruptions is 0**, so every eviction was refused and the drain timed out after 3 minutes. The PDB did its job
too well. The fix is to run more replicas than the budget requires (3 replicas with `minAvailable: 2` allows one
at a time) or use `maxUnavailable: 1`. DaemonSet Pods are skipped (`--ignore-daemonsets`) because they belong on
every node.

PDBs only stop **voluntary** disruptions like drains and autoscaler scale-downs. A node that crashes, or
**node-pressure eviction** (the kubelet evicting Pods when the node runs out of memory or disk), ignores them.

## Mission: Place, reserve and drain

Spread a 4-replica Deployment across zones and record where each Pod lands. Taint one node and show a Pod without a toleration staying Pending. Apply a PDB with minAvailable 2 to shop-web, try draining with 2 replicas, then with 3, and record the difference.

- You need: 11-spread.yaml, 11-gpu-only.yaml and 11-pdb.yaml
- You'll have: ~/scheduling.txt

```sh
$ kubectl apply -f 11-spread.yaml && kubectl rollout status deployment/spread
$ kubectl get pods -l app=spread -o custom-columns=POD:.metadata.name,NODE:.spec.nodeName > ~/scheduling.txt
$ kubectl apply -f 11-pdb.yaml && kubectl scale deployment shop-web --replicas=2
$ N=$(kubectl get pods -l app=shop-web -o jsonpath='{.items[0].spec.nodeName}')
$ kubectl drain $N --ignore-daemonsets --timeout=60s >> ~/scheduling.txt 2>&1; kubectl uncordon $N
$ kubectl scale deployment shop-web --replicas=3 && kubectl rollout status deployment/shop-web
$ kubectl drain $N --ignore-daemonsets --timeout=120s >> ~/scheduling.txt 2>&1; kubectl uncordon $N
```

The first drain should time out on the disruption budget; the second should complete.

## Try it

- List nodes with their zone label.
- Apply the spread Deployment and check which node each Pod landed on.
- Taint and label one node, apply the two Pods, and read why one stays Pending.
- Apply the PodDisruptionBudget and try to drain a node.
- Do the mini mission and keep `~/scheduling.txt`.

## Quiz

1. A node has the taint dedicated=batch:NoSchedule. Which Pods can be scheduled on it?
   - Any Pod
   - **Only Pods with a matching toleration** (answer)
   - No Pods at all
   Why: Taints repel; tolerations let a Pod accept the taint. A toleration doesn't attract the Pod, so pair it with a node selector or affinity.

2. A PodDisruptionBudget says minAvailable 2, and the Deployment has exactly 2 replicas. What happens when you drain a node?
   - The Pod is evicted immediately
   - **The eviction is refused, and the drain waits and can time out** (answer)
   - Both Pods restart
   Why: Allowed disruptions is 0, so voluntary evictions are blocked. Run more replicas than minAvailable, as the lab's timed-out drain shows.

3. What does topologySpreadConstraints with maxSkew 1 on topology.kubernetes.io/zone do?
   - Puts all Pods in one zone
   - **Keeps the number of Pods per zone within 1 of each other, so losing a zone doesn't take everything** (answer)
   - Limits Pods per node to 1
   Why: The lab's 4 Pods landed 2 and 2 across ap-south-1a and ap-south-1b.

## Resources

- [Kubernetes scheduler](https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/) (Kubernetes)
- [Taints and tolerations](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) (Kubernetes)
- [Pod topology spread constraints](https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/) (Kubernetes)
- [Safely drain a node](https://kubernetes.io/docs/tasks/administer-cluster/safely-drain-node/) (Kubernetes)
- [Node-pressure eviction](https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/) (Kubernetes)
