🛠️ Controllers in Kubernetes
Kubernetes controllers manage the lifecycle and availability of Pods. They ensure that the desired state (as defined by YAML or commands) is continuously reconciled with the current state in the cluster.
✅ Why Use Controllers?
While a Pod can be created manually, it won't automatically recover if it fails. Controllers automate this, ensuring your workloads are:
- Resilient (auto-restarted)
- Scalable (adjust replicas)
- Declarative (defined via YAML)
📦 ReplicaSet
A ReplicaSet ensures that a specified number of identical Pods are running at all times.
Example YAML
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: myapp-replicaset
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myimage
Commands
kubectl apply -f replicaset.yaml # Create ReplicaSet
kubectl get rs # List ReplicaSets
kubectl describe rs <name> # View details
kubectl edit rs <name> # Edit live
kubectl delete rs <name> # Delete
💡 Important Notes
- Ensure
selector.matchLabelsmatchestemplate.metadata.labels - ReplicaSets are rarely used directly; Deployments manage them
🚀 Deployment
A Deployment is the most commonly used controller. It manages ReplicaSets and provides features like:
- Rolling updates
- Rollbacks
- Declarative scaling
Create via Command
kubectl create deployment nginx --image=nginx
kubectl create deployment nginx --image=nginx --replicas=3
Generate YAML
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx-deploy.yaml
Apply YAML
kubectl apply -f nginx-deploy.yaml
Inspect & Manage
kubectl get deployments
kubectl describe deployment <name>
kubectl edit deployment <name>
kubectl delete deployment <name>
Handle Rollouts
kubectl rollout status deployment <name>
kubectl rollout undo deployment <name>
Common Issue Example
# Image error (e.g., typo)
kubectl describe pod <name> # Check Events section for ImagePullBackOff
🧠 Other Controllers
StatefulSet
- Manages stateful applications
- Maintains unique identity per Pod (e.g., persistent volume)
- Example: databases, Kafka, etc.
DaemonSet
- Ensures a Pod runs on every node
- Common use: log collectors, monitoring agents
Job & CronJob
- Job: Run once and exit successfully (e.g., DB migration)
- CronJob: Schedule recurring Jobs (e.g., backup every day)
✅ Summary
| Controller | Purpose |
|---|---|
| ReplicaSet | Maintain a stable set of identical Pods |
| Deployment | Manage ReplicaSets with updates/rollbacks |
| StatefulSet | Ordered, identity-aware Pods (stateful apps) |
| DaemonSet | One Pod per node |
| Job | One-time task execution |
| CronJob | Scheduled job execution |
Controllers bring automation, scalability, and resilience to your Kubernetes workloads. Use Deployments as your default choice unless you have specific needs (e.g., persistent state).