A DaemonSet is a controller in Kubernetes that ensures that each node in the cluster (or nodes matching a specific label selector) runs a copy of a Pod. DaemonSet is usually used to run cluster daemon processes, such as log collection, monitoring agents, storage volume plug-ins, etc. Here's how to control the number of Pods in a DaemonSet:
- Using Node Selector
By setting nodeSelector in the DaemonSet's spec, you can specify which nodes to run the Pod on. For example, if you want to run a Pod on a node with a specific label, you can do this:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: example-daemonset
spec:
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
nodeSelector:
key: value
containers:- name: example-container
image: example-image
- name: example-container
In this example, only nodes with the key=value label will run the Pod.
2. Use Node Affinity
Node affinity provides more fine-grained control. You can use nodeAffinity to specify which nodes a Pod should be scheduled on. For example:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: example-daemonset
spec:
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: key
operator: In
values:
- value
containers:
- name: example-container
image: example-image
In this example, only nodes that meet the key In [value] condition will run the Pod.
3. Use Tolerations
If there are Taints on some nodes, you can allow Pods to be scheduled to these nodes by setting Tolerations. For example:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: example-daemonset
spec:
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
tolerations:
- key: key
operator: Equal
value: value
effect: NoSchedule
containers:
- name: example-container
image: example-image
In this example, the Pod will tolerate nodes with key=value taint.
4. Update Strategy
DaemonSet supports rolling updates, and you can control the number of Pods during the update process by setting updateStrategy. For example:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: example-daemonset
spec:
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
containers:
- name: example-container
image: example-image
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 0
In this example, maxUnavailable is set to 1, which means that at most one Pod will be unavailable during the update process; maxSurge is set to 0, which means that no additional Pods will be created during the update process.
Through the above methods, you can flexibly control the number and scheduling strategies of Pods in the DaemonSet.