Advanced Scheduling: Placing Pods with Precision
9 min read
Advanced Scheduling: Placing Pods with Precision 🎯
Welcome back! So far, you've let the Kubernetes scheduler work its magic, placing your Pods wherever it sees fit. For the most part, it does a fantastic job. But what happens when "good enough" isn't good enough?
Sometimes, you need to be the boss. You might need to place a Pod on a node with specific hardware (like a GPU), keep certain workloads separate, or run a specific service on every single node.
That's where advanced scheduling comes in. It's how you give the scheduler a nudge—or a firm command—to place Pods with precision.
Let's dive into the three core tools you'll use to become a master of Pod placement.
1. Node Selectors and Node Affinity: Guiding Pod Placement 🚚
The Problem: I have a Pod that needs a powerful GPU for machine learning tasks. How do I make sure it only lands on nodes that actually have a GPU? I don't want it sitting on a general-purpose node, wasting resources and failing to run.
The Solution: We need a way to label our nodes and then tell our Pods to look for those labels.
First, The Building Block: Node Labels
Before you can select a node, you have to give it an identity. In Kubernetes, we do this with labels. Labels are simple key-value pairs you attach to objects, like nodes.
Imagine you're running a shipping company. Your nodes are delivery trucks. Some trucks are standard, but others are special—some have refrigeration, some are extra-large for heavy loads. You'd put a sticker (a label) on them to know what they are.
Let's say you have a node named worker-node-3 that has a shiny new GPU. You can label it like this:
# Label the node 'worker-node-3' with the key 'gpu' and value 'true'
kubectl label nodes worker-node-3 gpu=trueNow, that node has a "sticker" on it that says gpu=true. You can check the labels on a node anytime:
kubectl get nodes --show-labelsConcept 1: nodeSelector (The Simple Approach)
The easiest way to direct a Pod to a specific node is with nodeSelector. It's a field in your Pod's specification that says, "Only schedule me on a node that has all of these exact labels."
Here’s how you'd tell a Pod to only run on a node with our gpu=true label:
pod-with-nodeselector.yaml:
apiVersion: v1
kind: Pod
metadata:
name: gpu-workload
spec:
containers:
- name: cuda-container
image: nvidia/cuda:11.0.3-base-ubuntu20.04
nodeSelector:
gpu: "true"What happens? The scheduler will now only consider nodes with the label gpu: "true" for this Pod. If no nodes have that label, the Pod will remain in a Pending state forever. It’s simple and effective for direct requirements.
Concept 2: nodeAffinity (The Flexible & Powerful Successor)
nodeSelector is great, but it can be a bit rigid. What if you want more complex rules?
- "I prefer a node with a GPU, but if there isn't one, just put me on any available node."
- "Put me on any node that has a high-speed SSD, but not on one that is in the
us-east-1aavailability zone."
This is where nodeAffinity shines. It's a more expressive and flexible way to define placement rules. It comes in two main flavors:
A. requiredDuringSchedulingIgnoredDuringExecution (The "Must Have")
This is the "hard" requirement. The rule must be met for the Pod to be scheduled. It's the spiritual successor to nodeSelector but with a more powerful syntax.
Let's rewrite our GPU example using this:
pod-with-required-affinity.yaml:
apiVersion: v1
kind: Pod
metadata:
name: gpu-workload-required
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: gpu
operator: In
values:
- "true"
containers:
- name: cuda-container
image: nvidia/cuda:11.0.3-base-ubuntu20.04The operator: In checks if the gpu label's value is in the provided list. Other operators include NotIn, Exists, and DoesNotExist, giving you much more control.
🧠 A Quick Note: The long name IgnoredDuringExecution means that if a node's labels change after the Pod is already running, Kubernetes won't kick the Pod off the node. It's a one-time check during scheduling.
B. preferredDuringSchedulingIgnoredDuringExecution (The "Nice to Have")
This is the "soft" requirement. The scheduler will try its best to follow the rule, but if it can't, it will schedule the Pod elsewhere. This is perfect for optimization without sacrificing availability.
Imagine you want to place your pods on nodes with fast SSDs if possible.
pod-with-preferred-affinity.yaml:
apiVersion: v1
kind: Pod
metadata:
name: web-server-preferred
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: disk-type
operator: In
values:
- ssd
containers:
- name: nginx
image: nginxHow does this work?
- The
weight(from 1 to 100) tells the scheduler how strongly you prefer this rule. A higher weight means a stronger preference. - If a node with the
disk-type: ssdlabel is available, it gets a higher "score" from the scheduler. - If no such node is available, the Pod will be scheduled on any other available node. No drama.
Industry Practice: For new development, prefer nodeAffinity over nodeSelector. Its expressive syntax provides far more control and flexibility for real-world scenarios.
2. Taints and Tolerations: Repelling Pods from Specific Nodes ⛔
The Problem: We just learned how to attract Pods to certain nodes. But what about the opposite? I have a set of nodes dedicated to running critical monitoring services, and I don't want any regular application Pods to be scheduled there. How do I keep them away?
The Solution: You taint the node to repel Pods, and give specific Pods a toleration to ignore that taint. Taints and tolerations work together like a lock and key.
Concept 1: Taints (The "Keep Out" Sign)
A taint is a property you apply to a node that marks it as "repulsive" to most Pods. The scheduler will not place any Pod on a tainted node unless that Pod has a matching toleration.
Let's taint a node named monitoring-node-1 to reserve it for special workloads.
# Taint the node with key=value:Effect
kubectl taint nodes monitoring-node-1 special-workload=true:NoScheduleThis command adds a taint with:
- Key:
special-workload - Value:
true - Effect:
NoSchedule
There are three possible effects for a taint:
NoSchedule: The most common effect. No new Pods will be scheduled on this node unless they have a matching toleration. Existing Pods already on the node are not affected.PreferNoSchedule: A "soft" version. The scheduler will try to avoid placing a Pod on this node but will use it if no other nodes are available.NoExecute: The strictest effect. No new Pods are scheduled, and any existing Pods on the node that do not tolerate the taint are evicted (kicked out). This is often used automatically by Kubernetes to drain nodes that become unhealthy (e.g., due to network issues or disk pressure).
Concept 2: Tolerations (The "Special Pass") 🔑
A toleration is a property you add to a Pod's specification that allows it to be scheduled on a node with a matching taint. It's the Pod's way of saying, "I see that 'Keep Out' sign, but I have a special pass."
Let's create a Pod that can run on our tainted monitoring-node-1.
pod-with-toleration.yaml:
apiVersion: v1
kind: Pod
metadata:
name: my-monitoring-agent
spec:
containers:
- name: agent-container
image: busybox
args:
- /bin/sh
- -c
- "sleep 3600"
tolerations:
- key: "special-workload"
operator: "Equal"
value: "true"
effect: "NoSchedule"Because this Pod has a toleration that perfectly matches the taint on monitoring-node-1, the scheduler is now allowed to place it there.
Real-World Use Cases:
- Dedicated Nodes: Taint a group of nodes to reserve them for a specific team or application.
- Nodes with Special Hardware: Taint nodes with GPUs to ensure only Pods that need them (and have the right toleration) can be scheduled there, leaving room for those critical workloads.
- Node Maintenance: Before performing maintenance, you can add a
NoExecutetaint to a node to safely evict all its Pods so they can be rescheduled elsewhere.
3. DaemonSets: Ensuring a Pod Runs on Every Single Node 🤖
The Problem: I need to run a log collection agent on every single node in my cluster to gather logs. When a new node joins the cluster, it should automatically get this agent. Managing this with a Deployment would be a nightmare.
The Solution: This is precisely the job for a DaemonSet.
A DaemonSet is a Kubernetes controller that ensures a copy of a specific Pod is running on all (or a subset of) nodes in a cluster. When you add a new node, the DaemonSet automatically deploys your Pod to it. When a node is removed, the Pod is cleaned up. It's a "fire and forget" solution for node-level services.
How it Works (Under the Hood): The DaemonSet controller bypasses the default scheduler for its basic function. It watches for new nodes and creates Pods on them. It also automatically adds certain tolerations to its Pods, such as tolerating the node.kubernetes.io/unschedulable taint, so that its Pods can even be placed on nodes that are cordoned off for maintenance.
Here is an example of a DaemonSet that could run a simple log collector:
fluentd-daemonset.yaml:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluentd-log-collector
labels:
k8s-app: fluentd-logging
spec:
selector:
matchLabels:
name: fluentd-log-collector
template:
metadata:
labels:
name: fluentd-log-collector
spec:
tolerations:
# These tolerations are to have the daemonset run on control-plane nodes
# Remove them if your control-plane nodes should not run pods
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
- key: node-role.kubernetes.io/master
operator: Exists
effect: NoSchedule
containers:
- name: fluentd
image: fluent/fluentd:v1.14-debianOnce you apply this YAML, Kubernetes will ensure that a fluentd-log-collector Pod is running on every eligible node in your cluster.
Hands-on Industry Use Cases:
DaemonSets are the backbone of a healthy cluster. You'll see them used everywhere for:
- Log Collection: Running agents like Fluentd, Logstash, or Filebeat.
- Node Monitoring: Deploying monitoring agents like Prometheus Node Exporter or the Datadog Agent.
- Network Plugins: Services like Calico or Weave often run as DaemonSets to manage the network on each node.
- Cluster Storage: Storage solutions like GlusterFS or Ceph deploy daemons to each node to provide a distributed filesystem.
References for Extra Reading
- Assigning Pods to Nodes: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/
- Taints and Tolerations: https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/
- DaemonSets: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
- Labels and Selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
Challenge
You are a DevOps engineer tasked with deploying a multi-component application. The Kubernetes cluster has three distinct types of nodes:
- GPU Nodes: Labeled with
hardware=gpu-v100and tainted withgpu-workload=true:NoSchedule. - Storage Nodes: Labeled with
storage=ssd. - General-Purpose Nodes: Have no specific labels or taints.
Your task is to write a single YAML file containing three Kubernetes resource manifests, separated by ---, to deploy the application components according to the following strict scheduling requirements:
ml-trainer(Deployment): A machine learning workload.- It must run exclusively on nodes that have the
hardware=gpu-v100label. - It must be able to run on the GPU nodes, despite their taint.
- The container should use the image
nvidia/cuda:11.0-base.
- It must run exclusively on nodes that have the
log-collector(DaemonSet): A critical logging agent.- A replica of this pod must run on every single node in the cluster, including the tainted GPU nodes.
- The container should use the image
fluent/fluentd:v1.12-debian.
redis-cache(Deployment): A backend cache service.- It should prefer to run on nodes with the
storage=ssdlabel. Assign this preference aweightof 50. - If no SSD nodes are available, it should be schedulable on any other node.
- The container should use the image
redis:6.2-alpine.
- It should prefer to run on nodes with the
Expected result
Your final submission should be a single, valid YAML string containing three Kubernetes manifests separated by ---.
Manifest 1: ml-trainer Deployment
The spec.template.spec section must contain:
- An
affinityblock withnodeAffinityconfigured for a required placement. It must userequiredDuringSchedulingIgnoredDuringExecutionto select nodes where the labelhardwarehas the valuegpu-v100. - A
tolerationsarray with an entry that allows the pod to be scheduled on nodes with the taintkey: gpu-workload,value: true,effect: NoSchedule.
Manifest 2: log-collector DaemonSet
The spec.template.spec section must contain:
- A
tolerationsarray that allows the pod to be scheduled on any node, including those with thegpu-workloadtaint. A common way to achieve this is to tolerate the keygpu-workloadwith theExistsoperator.
Manifest 3: redis-cache Deployment
The spec.template.spec section must contain:
- An
affinityblock withnodeAffinityconfigured for a preferred placement. It must usepreferredDuringSchedulingIgnoredDuringExecution. - The preference rule must have a
weightof50and select nodes where the labelstoragehas the valuessd.