Kubernetes - ReplicaSet & DaemonSet

Kubernetes - ReplicaSet & DaemonSet

ReplicaSet is a Kubernetes object designed to maintain a specified number of pod replicas running at any given time. It ensures that a defined number of identical pods are always available, even in the event of failures. This feature is crucial for achieving high availability and reliability for your applications.

Creating a ReplicaSet

Below is an example of a simple ReplicaSet configuration that runs two instances of an Nginx container:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: my-replicaset
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: cont1
        image: httpd
        ports:
        - containerPort: 80

In this example:

  • replicas: 2 specifies the desired number of pod replicas.

  • The selector matches pods with the label app: nginx.

  • The template defines the pod’s specifications, including the container image (httpd) and the port (80).

Apply the ReplicaSet:

To deploy this ReplicaSet, save the above YAML content in a file named my-replicaset.yaml and apply it using the following command:

kubectl apply -f my-replicaset.yaml

Verifying the ReplicaSet

After creating the ReplicaSet, you can verify its status and check that the desired number of pods are running:

kubectl get replicaset

kubectl get pods -o wide


Introduction to DaemonSet

DaemonSet is another crucial Kubernetes object, but unlike a ReplicaSet, it ensures that a particular pod runs on all (or a specific subset of) nodes in your cluster. This is especially useful for running background tasks or system-level services, such as log collection or monitoring agents, across all nodes.

Creating a DaemonSet

Below is an example of a DaemonSet configuration that ensures an HTTPD container runs on all nodes:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: my-daemonset
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: cont1
        image: httpd
        ports:
        - containerPort: 24224

In this example:

  • The selector matches pods with the label app: nginx.

  • The template defines the pod’s specifications, ensuring that an HTTPD container runs on every node with the specified port (24224).

Apply the DaemonSet using the following command:

kubectl apply -f daemonset.yaml

Verifying the DaemonSet

To ensure the DaemonSet is correctly running on all nodes, you can use the following commands:

kubectl get daemonset

kubectl get pods -o wide


Conclusion

Kubernetes ReplicaSet and DaemonSet are vital components for maintaining the desired state of your applications across your cluster. By understanding how to create and manage these objects, you can ensure greater control, reliability, and scalability for your Kubernetes-based applications.