Kubernetes Services and Service Discovery

ยท

4 min read

Kubernetes Services and Service Discovery

Kubernetes Services

Kubernetes services Allow you to dynamically access a group of replica Pods via IP and Port from your network and define a name for the service.

In Kubernetes, a Service is an abstraction layer that sits between the application's internal logic and the outside world, providing a stable IP address and DNS name for a set of Pods. It enables communication between various components of the application running on different Pods, abstracting the underlying IP addresses and ports.

Cluster IP - It is the default Kubernetes service used for internal communication within the cluster.

NodePort - It will open ports on each node and traffic will be forwarded to the service through the random port. And I can access the service (Pod) with the node IP + Defined port.

LoadBalancer - It is a type that forwards all external traffic to a service through this type. And I can access the service (Pod) with the node name only.

External Name - it is a type used to access a service internally that is hosted outside the cluster through DNS CName or A record.

How to expose Kubernetes workloads??

  1. Create a deployment: A deployment is a Kubernetes resource that manages a set of pods. You can create a deployment using a YAML or JSON file that describes the desired state of your deployment.

  2. Create a service: A service is a Kubernetes resource that provides a stable IP address and DNS name for your deployment. You can create a service using a YAML or JSON file that describes the desired state of your service.

  3. Expose the service: Once you have created the service, you can expose it to the outside world using a service type. There are several service types available in Kubernetes, including ClusterIP, NodePort, and LoadBalancer.

Create a Deployment for the Nginx Web Server

  • Let's create a deployment.yaml file for nginx web server deployment.

      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: nginx-deployment
      spec:
        selector:
          matchLabels:
            app: Web-Server
        replicas: 3
        template:
          metadata:
            labels:
              app: Web-Server
          spec:
            containers:
              - name: nginx-container
                image: nginx:latest
    

  • Now Expose the web server using the "Node Port" service, for this, we need to create nginx-service.yaml.

      apiVersion: v1
      kind: Service
      metadata:
        name: nginx-nodePort-service
      spec:
        selector:
          app: Web-Server
        ports:
          - name: http
            port: 80
            targetPort: 80
        type: NodePort
    

  • Now Access the Exposed Web server.

      kubectl get service node-service
    

Discover Services and Pods within a Kubernetes cluster

  • Kubernetes provides built-in DNS-based service discovery, allowing services and pods to communicate with each other using DNS names.

  • By default, each Service in a Kubernetes cluster is assigned a DNS name based on its name and namespace.

  • Similarly, pods are assigned a DNS name based on their name and namespace.

Discovering a Service Using DNS

Let's say we have a Service named "node-service" deployed in the "default" namespace. We can discover this Service using DNS. Here's an example Python code snippet to resolve the DNS and retrieve the IP address of the Service:

import socket

service_host = "node-service.default.svc.cluster.local"
service_port = 80

service_address = socket.gethostbyname(service_host)
print(f"Service IP: {service_address}")

In the above code snippet, replace node-service with the actual name of your Service, and modify the namespace and port accordingly. Running this code will resolve the DNS name node-service.default.svc.cluster.local and print the corresponding IP address of the Service.

Discovering a Pod using DNS

Similarly, let's assume we have a Pod named "node-service" running in the "default" namespace. We can discover this Pod using DNS. Here's an example Python code snippet to resolve the DNS and retrieve the IP address of the Pod:

import socket

pod_host = "POD_NAME.default.pod.cluster.local"
pod_port = 8080

pod_address = socket.gethostbyname(pod_host)
print(f"Pod IP: {pod_address}")

Replace POD_NAME with the actual name of your Pod, and adjust the namespace and port as necessary. Executing this code will resolve the DNS name POD_NAME.default.pod.cluster.local and display the IP address of the Pod.

To test the above code snippets, ensure that you have the necessary Python environment set up with the socket module available. Execute the code and observe the output, which will provide the IP addresses of the discovered Service and Pod.

Environment Variables

Kubernetes sets environment variables for each service and pod within the cluster, allowing easy access to their information. You can access these environment variables from within a container to discover services and pods. Here's an example code snippet in Python to access environment variables:

import os

service_host = os.getenv("MY_SERVICE_HOST")
service_port = os.getenv("MY_SERVICE_PORT")

if service_host and service_port:
    print(f"Service Host: {service_host}")
    print(f"Service Port: {service_port}")
else:
    print("Service environment variables not found")

In the code snippet above, the os.getenv() function retrieves the values of environment variables such as MY_SERVICE_HOST and MY_SERVICE_PORT. Adjust the variable names to match the specific environment variables used in your deployment. If the environment variables are found, their values will be printed. Otherwise, a message indicating their absence will be displayed.


Thank you ๐Ÿ˜Š

Happy Learning ๐Ÿ“š

Vishal Ranmale

https://www.linkedin.com/in/vishal-ranmale-907307114/

ย