In this lesson, you will learn how to use a ReplicaSet to enforce the desired number of identical Pods running in your cluster.
Up until now, you have managed individual Pods. However, in a real-world environment, creating Pods manually is fragile. If a node fails or a Pod crashes, that instance is gone forever. A ReplicaSet solves this by acting as a "guaranteed headcount" controller. You tell the Kubernetes API Server how many copies (replicas) of a specific Pod you want, and the system works tirelessly to ensure that number is always met.
The ReplicaSet Manifest
A ReplicaSet manifest consists of three main pillars: replicas (the count), selector (how to identify the pods), and template (the blueprint for the Pods).
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: web-app-replicas
spec:
replicas: 3
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: nginx
image: nginx
How it Works
- The Count: The
replicas: 3field defines your desired state. The Controller Manager constantly monitors this. - The Selector: The
selectortells the ReplicaSet which Pods it is responsible for. It looks for any Pod with the labelapp: frontend. - The Template: If the Controller Manager sees only two Pods matching that label but the desired state is three, it uses the
templatesection to spin up a new Pod immediately. If you manually delete one of the three Pods, the Controller Manager notices the missing Pod and schedules another one to replace it, ensuring the "desired state" is reconciled.
This declarative approach allows you to scale your application simply by changing the replicas integer, allowing the Kubernetes control loop to handle the heavy lifting of creating or removing the necessary Pods for you.
Key Takeaway: A ReplicaSet ensures that a specified number of Pods matching a defined selector are always running, automatically reconciling the actual cluster state to match your declared desired state.