7th Week :- Mastering Kubernetes Services: ReplicaSet, Deployment & Service Types Explained

Lav kushwahaLav kushwaha
7 min read

πŸ” What is a ReplicaSet?

πŸ“– Definition:

A ReplicaSet (RS) is a Kubernetes controller that ensures a specific number of identical Pods are always running. If a pod crashes or gets deleted, the ReplicaSet automatically spins up a new one to maintain the declared replica count.


πŸ” Why is ReplicaSet Needed?

  • Ensures High Availability: If a pod crashes, RS recreates it instantly.

  • Scalability: You can scale apps by increasing replica counts.

  • Self-Healing: RS replaces failed or accidentally deleted pods automatically.

  • Foundation for Deployment: Used internally by Deployments to manage pods.


πŸ›  YAML Example:

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

πŸ§ͺ Real-World Use Case:

You're running a front-end app in production and want to ensure at least 3 instances (pods) are always available. If any fail, they should auto-recover without manual effort.


πŸ’» Commands:

kubectl apply -f replicaset.yaml     # Create ReplicaSet
kubectl get replicaset               # Check ReplicaSet status
kubectl scale rs frontend-rs --replicas=5  # Scale up to 5 pods
kubectl delete rs frontend-rs       # Delete ReplicaSet

⚠️ Limitations:

  • No Version Control: You can’t do rolling updates.

  • Not Ideal for CI/CD: You need to manually delete and recreate ReplicaSets for updates.

  • No Rollback Support: You cannot rollback to previous versions.


πŸš€ What is a Deployment?

πŸ“– Definition:

A Deployment is a higher-level controller that manages ReplicaSets and provides capabilities like rolling updates, version tracking, and rollback. It’s the most commonly used K8s object for managing stateless applications.


πŸ” Why Use Deployment?

  • βœ… Declarative Updates: You define the desired state, and Kubernetes ensures it's met.

  • βœ… Rolling Updates: Update pods incrementally with zero downtime.

  • βœ… Rollback Support: Revert to a previous version easily.

  • βœ… Scaling: Adjust replicas dynamically.


πŸ›  YAML Example:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.21
        ports:
        - containerPort: 80

πŸ§ͺ Real-World Use Case:

You want to deploy an updated version of your backend API. Using a Deployment, you can roll out the update gradually. If anything goes wrong, roll back safely.


πŸ’» Commands:

kubectl apply -f deployment.yaml
kubectl get deployments
kubectl rollout status deployment/my-nginx-deployment
kubectl rollout history deployment/my-nginx-deployment
kubectl rollout undo deployment/my-nginx-deployment
kubectl scale deployment my-nginx-deployment --replicas=5
kubectl delete deployment my-nginx-deployment

⚠️ Limitations:

  • Not suitable for stateful apps that require stable identity (use StatefulSets instead).

  • Only supports stateless app patterns.

  • Needs a Service to expose pods to other apps or users.


🌐 What is a Service in Kubernetes?

πŸ“– Definition:

A Service is a Kubernetes abstraction that defines a logical set of pods and a policy by which to access them β€” usually via a stable IP address and DNS name.


πŸ” Why is Service Needed?

  • πŸ”„ Load Balancing: Automatically distributes traffic across pods.

  • 🧭 Stable Endpoint: Pods can die and restart, but the service IP remains the same.

  • 🌐 Accessibility: Expose apps internally or to the internet.

  • πŸ”— Service Discovery: Other components can reach it via DNS (my-service.default.svc.cluster.local).


πŸ“¦ Types of Services

TypeDescription
ClusterIP (default)Accessible only within the cluster
NodePortExposes app on a static port on each node
LoadBalancerProvides external IP using cloud provider's LB
ExternalNameMaps service to an external DNS name

1️⃣ ClusterIP (Default)

πŸ“– What it is:

The default service type. It gives an internal IP that is accessible only within the cluster.

βœ… Use Cases:

  • Internal communication between microservices

  • Backend DB or API called by other services

πŸ§ͺ YAML Example:

apiVersion: v1
kind: Service
metadata:
  name: backend-service
spec:
  selector:
    app: backend
  ports:
    - protocol: TCP
      port: 80         # Service port
      targetPort: 8080 # Container port

🌐 Access:

Other services/pods access it using:

http://backend-service

🧱 Diagram:

[frontend pod] ---> [backend-service: ClusterIP] ---> [backend pod]

⚠️ Limitations:

  • Cannot be accessed from outside the cluster

  • Use NodePort or Ingress if needed externally


2️⃣ NodePort

πŸ“– What it is:

A NodePort service exposes the app on each worker node’s IP at a static port (30000–32767). You can then access the app via:

http://<NodeIP>:<NodePort>

βœ… Use Cases:

  • Quick testing of services locally (e.g., Minikube)

  • Basic external access on self-hosted clusters

  • Demo/staging environments

πŸ§ͺ YAML Example:

apiVersion: v1
kind: Service
metadata:
  name: nodeport-service
spec:
  type: NodePort
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30080

🧱 Diagram:

User Browser
     ↓
 http://<NodeIP>:30080
     ↓
[NodePort Service] ---> [Pod]

⚠️ Limitations:

  • Static port range (30000-32767)

  • Exposes service on all nodes (even if the pod is running on just one)

  • No advanced traffic routing or SSL (use Ingress)


3️⃣ LoadBalancer

πŸ“– What it is:

A LoadBalancer service creates an external load balancer (from your cloud provider), which routes traffic to your NodePort or ClusterIP services.

βœ… Use Cases:

  • Publicly accessible services in production

  • Auto-scaled apps hosted on AWS, GCP, Azure, etc.

🌩️ Cloud Providers Required:

Works only on:

  • AWS (Elastic Load Balancer)

  • GCP (Cloud Load Balancing)

  • Azure (Load Balancer)

  • Or use MetalLB for bare metal clusters

πŸ§ͺ YAML Example:

apiVersion: v1
kind: Service
metadata:
  name: loadbalancer-service
spec:
  type: LoadBalancer
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 8080

🧱 Diagram:

User Browser
     ↓
[Cloud Load Balancer (Public IP)]
     ↓
[LoadBalancer Service] ---> [Pod(s)]

⚠️ Limitations:

  • Cloud-only

  • Provisioning time is higher

  • May incur cost (in production environments)

  • One LB per service = not scalable in large-scale setups (consider Ingress)βœ… Summary Table

4️⃣ ExternalName

πŸ“– What it is:

This service doesn’t route traffic but acts as a CNAME (DNS alias) for an external service.

βœ… Use Cases:

  • Redirect Kubernetes traffic to external databases or APIs

  • Use familiar DNS names inside your cluster

πŸ§ͺ YAML Example:

apiVersion: v1
kind: Service
metadata:
  name: my-sql-service
spec:
  type: ExternalName
  externalName: mydb.example.com

🌐 Usage:

Your app inside the cluster can access:

http://my-sql-service

Which internally maps to:

http://mydb.example.com

🧱 Diagram:

[pod] ---> [ExternalName service] --> [external DNS: mydb.example.com]

⚠️ Limitations:

  • DNS-based only; no ports or selectors

  • Cannot load balance or health check


πŸ”„ Summary Table of Service Types

TypeAccess LevelTraffic OriginReal IP HandlingLoad BalancedExternal Access
ClusterIPInternal onlyOther cluster servicesInternal IPβœ… (between pods)❌
NodePortExternal on NodeBrowser / External AppNode IP + Portβœ…βœ… (basic)
LoadBalancerPublic InternetUser’s browserPublic IPβœ… (cloud)βœ… (prod-ready)
ExternalNameInternal DNSInternal PodsCNAMEβŒβœ… (DNS only)

🧠 Choosing the Right Service Type

ScenarioBest Type
Microservice-to-microserviceClusterIP
Dev/test external accessNodePort
Production public accessLoadBalancer
Connect to 3rd-party APIExternalName

ComponentPurposeCan ScaleCan UpdateStable AccessExposes to Users
ReplicaSetMaintain pod countβœ…βŒβŒβŒ
DeploymentManage ReplicaSet & versionβœ…βœ…βŒβŒ
ServiceExpose pods to networkβŒβŒβœ…βœ… (depends on type)
0
Subscribe to my newsletter

Read articles from Lav kushwaha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lav kushwaha
Lav kushwaha