Day 04 || Labels and Selectors in Kubernetes

Day 04 || Labels and Selectors in Kubernetes

Labels are key-value pairs assigned to Kubernetes objects, such as Pods, Nodes, and Services. They categorize and identify resources. For instance, a Pod can have a label like app: frontend. This helps organize, filter, and group resources.

Selectors are used to filter Kubernetes objects based on labels. Selectors ensure that operations, such as scaling or monitoring, apply to specific resources. For example:

yamlCopy codeselector:
  matchLabels:
    app: frontend

This selector targets all objects labeled app: frontend.

Use Case Example
When deploying a microservices application, you can assign labels to differentiate components like app: frontend, app: backend, and app: database. Use selectors to manage Pods selectively for scaling or monitoring.


ReplicationController

ReplicationController (RC) ensures a specified number of Pod replicas are running at all times. It automatically creates or deletes Pods to maintain the desired state.

YAML Example

yamlCopy codeapiVersion: v1
kind: ReplicationController
metadata:
  name: frontend-controller
spec:
  replicas: 3
  selector:
    app: frontend
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: nginx
        ports:
        - containerPort: 80

Commands to Apply and Verify

  • Apply the configuration:

      bashCopy codekubectl apply -f frontend-controller.yml
    
  • Check the status:

      bashCopy codekubectl get rc
    
  • Describe the controller:

      bashCopy codekubectl describe rc frontend-controller
    

ReplicaSet

ReplicaSet (RS) is an evolved form of ReplicationController with additional support for set-based selectors. It ensures a specified number of Pod replicas are running, similar to RC but more flexible in targeting Pods.

YAML Example

yamlCopy codeapiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: frontend
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: nginx
        ports:
        - containerPort: 80

Commands to Apply and Verify

  • Apply the ReplicaSet:

      bashCopy codekubectl apply -f frontend-replicaset.yml
    
  • Scale the ReplicaSet:

      bashCopy codekubectl scale --replicas=5 rs/frontend-replicaset
    
  • Delete a Pod and observe auto-replacement:

      bashCopy codekubectl delete pod <pod-name>
    

Scaling and Fault Tolerance
ReplicationController and ReplicaSet are crucial for scaling applications and ensuring high availability by maintaining the desired number of replicas during failures or updates.

By mastering these concepts, you'll effectively manage Kubernetes workloads.

Did you find this article valuable?

Support Aqib Hafeez(DevOps enthusiast) by becoming a sponsor. Any amount is appreciated!