Kubernetes Services and Service Discovery

Kubernetes Services:

Kubernetes Services are a way to provide network access to a set of Pods in a Kubernetes cluster. A Service provides a stable IP address and DNS name that other parts of the application can use to access the Pods. Services can be used to expose workloads to other parts of the application, to external users over the internet, or to other Kubernetes clusters.

There are four types of Services in Kubernetes:

  1. ClusterIP: This is the default Service type, which creates a virtual IP address that can be used to access the Service within the Kubernetes cluster. This Service type is only accessible from within the cluster.

  1. NodePort: This Service type exposes the Service on a specific port on each node in the cluster. This allows external clients to access the Service using the node's IP address and the specified port.

  1. LoadBalancer: This Service type provisions a load balancer in a cloud environment to distribute traffic to the Pods that make up the Service. This allows external clients to access the Service using a stable IP address and DNS name.

Service Discovery:

Service discovery is the process by which a client or application can dynamically locate and connect to services in a distributed system. In a Kubernetes cluster, service discovery is used to locate the Pods that make up a Service.

Kubernetes provides several mechanisms for service discovery, including DNS-based service discovery and environment variables.

DNS-based service discovery:

In this example, the Deployment creates three replicas of a Pod running an application called my-app. The Service exposes this application on port 80 and is configured to use DNS-based service discovery to locate the Pods that make up the Service.

When a client wants to connect to my-service, it can use the DNS name my-service.default.svc.cluster.local, where default is the namespace in which the Service is deployed. The DNS resolver within the Kubernetes cluster will resolve this DNS name to the IP address of one of the Pods that make up the Service, allowing the client to connect to the application running on that Pod.

Environment variables:

In this example, the Deployment creates three replicas of a Pod running an application called my-app. The Pod is configured with two environment variables, MY_SERVICE_HOST and MY_SERVICE_PORT, which is set to the name of the Service (my-service) and the port number that the Service is exposed on (80), respectively.

The Service exposes the application running in the Pod on port 80. When the application needs to connect to the my-service, it can use the MY_SERVICE_HOST and MY_SERVICE_PORT environment variables to determine the IP address and port of the Service.