Wednesday, September 2, 2026

Creating a Service in Kubernetes

 


What is a Service?


A Service is a Kubernetes object that provides a stable IP address and DNS name to access Pods.


Since Pod IP addresses can change when Pods are recreated, a Service acts as a fixed endpoint for accessing the application.




Why Do We Need a Service?


Suppose you have 3 Pods: Pod-1/Pod-2/Pod-3


If Pod-1 crashes, Kubernetes creates a new Pod with a different IP address.



Without a Service:


Users need to know individual Pod IPs.

Pod IPs keep changing.



With a Service:


Users connect to one stable IP/DNS.

The Service automatically forwards traffic to available Pods.




Service YAML Example


apiVersion: v1

kind: Service

metadata:

  name: nginx-service


spec:

  selector:

    app: nginx


  ports:

  - protocol: TCP

    port: 80

    targetPort: 80


  type: ClusterIP




Understanding the YAML


selector - The Service finds all Pods having (labels:  app: nginx)

selector:

  app: nginx



port - The port exposed by the Service.

port: 80



targetPort - The port on the container where the application is running.

targetPort: 80



type - Defines how the Service is exposed.

type: ClusterIP




How Service Works (The Service distributes incoming requests among all available Pods.)


nginx-service

|

------------------

|       |        |

Pod1   Pod2    Pod3




Create a Service


kubectl apply -f service.yaml

kubectl get svc

kubectl get services




Types of Services



1. ClusterIP (Default)


Accessible only inside the Kubernetes cluster.


type: ClusterIP




2. NodePort


Exposes the application on a port of every worker node. <Node-IP>:30000


type: NodePort




3. LoadBalancer


Creates an external load balancer (AWS, Azure, GCP). [Access: External IP]


type: LoadBalancer


No comments:

Post a Comment

testing