Kubernetes Services -1 ClusterIP

Kubernetes Services -1  ClusterIP

A Service in Kubernetes is an object like a Pod, Deployment, or ConfigMap.

Services are used to enable communication between Pods, whether within the same Kubernetes cluster or with external resources.

In the screenshot below, you can see that we are running a curl command using the private IPs of backend pods inside a frontend pod.

This means that communication between pods within the same cluster can occur using their private IPs. This leads us to the following question.

So why do we need service ?

If communication between pods can happen using private IPs, why do we need a service to enable communication between pods? The answer is simple: multiple pods are created and destroyed within a cluster, and each pod gets a unique IP. Let's say the frontend pod is your web app's frontend, and the backend pods are the databases running in a replica set. If one of the backend pods goes down, a new pod will be created with a new IP. The application data inside the container doesn't change, but you would have to update the application code to point to the new pod.

So what can we do ?

Here, it doesn't matter if traffic is sent to backend1 or backend2 because the data is the same. Instead of maintaining 2-3 backend IPs in the application code, we will replace them with the IP of the service. This service will redirect the traffic to the backend pods.

apiVersion: v1
kind: Service
metadata:
  name: my-service  # Service Name 
spec:
  selector: # Service will select Pods with below label as its endpoint(where it will redirect traffic)
    service_select_label: MyApp
  ports:
    - protocol: TCP
      port: 8080   # Port where Service is Listening 
      targetPort: 80  # Port where pod is listening

Using the above YAML, create the following service:

You can see two IPs with port 80 in the Endpoints. If you check the pods, you'll notice that these IPs are the private IPs of the pods. Since the backend pods match the selector label, these two pods are added as Endpoints of the service.

The service listens on port 8080 and forwards the traffic to port 80 of the backend pods. Now, when we try to curl the service IP with its port, we can see that sometimes we are redirected to backendpod1 and sometimes to backendpod2.

This service IP is private and can only be used within the cluster.

The service that uses private IPs for communication between pods and other resources within the cluster is called a ClusterIP service & this default service type in Kubernetes.