Creating the ReplicaSet YAML File
Start by creating the “ReplicaSets” directory and then create a file named “replica-set.yaml” inside it. Begin your file by specifying the appropriate API version for ReplicaSets, which isapps/v1, followed by setting the kind as ReplicaSet.
Below is a sample YAML snippet for the ReplicaSet. The metadata includes the ReplicaSet’s name (myapp-replicaset) and a label (app: myapp). Within the spec section, Visual Studio Code’s YAML extension may automatically add a selector field. Here, we are using the matchLabels option so that it matches the label in our previously created Pods. For instance, if your Pod’s definition uses a label such as env: production, include the same label in the ReplicaSet selector.
After defining the selector, specify the number of desired replicas (three in this example) and include the Pod template, which is copied from the original Pod YAML file. When pasting, ensure the indentation is correct; in Visual Studio Code, you can select the pasted block (except the first line) and press Tab twice to adjust the indentation.
Below is the sample YAML for our ReplicaSet, followed by the original Pod definition for reference:
The label defined in the ReplicaSet’s metadata (e.g.,
app: myapp) is not used for matching. Ensure that the label in the Pod template and the selector (here, env: production) match exactly to allow the ReplicaSet to manage the pods properly.Deploying the ReplicaSet
- Save the “replica-set.yaml” file.
-
Open your terminal, navigate to the project root where the “ReplicaSets” directory is located, and verify the file exists:
-
Use
catto inspect the file content and confirm its correctness: -
Create the ReplicaSet with the following command:
-
Check the status of the ReplicaSet:
Expected output:
-
List the pods to further validate:
Expected output:
myapp-replicaset), making it easy to identify managed pods.
Pod Deletion and Automatic Replacement
To verify that the ReplicaSet maintains the desired number of pods, delete one of them. For example:Creating a Pod with Matching Labels
Now, consider what happens if you manually create a Pod that uses a label matching the ReplicaSet’s selector. Use the following Pod definition saved as “nginx.yaml”:Updating a ReplicaSet
To update your ReplicaSet—for instance, changing the number of replicas from 3 to 4—run:spec section and update the replica count:
Scaling with kubectl scale
Alternatively, you can scale the ReplicaSet without editing the configuration file by using thekubectl scale command. To scale down the ReplicaSet to two replicas, run:
This lesson demonstrated how to create, manage, update, and scale a ReplicaSet in Kubernetes. Using ReplicaSets ensures that the desired number of pod replicas are consistently maintained, promoting high availability in your deployments.