Kubernetes Services act as an abstraction layer to expose Pods to the network, either within the cluster or externally. They offer a stable IP and DNS name, which routes client requests to the appropriate Pods.

Service Types and Their Use Cases

  1. ClusterIP: Exposes the service within the cluster.

    • Use Case: Internal applications like databases.
    kubectl apply -f clusterip-service.yaml
    
  2. NodePort: Exposes the service on a static port on each Node.

    • Use Case: External access to a service, not preferable for production.
    kubectl apply -f nodeport-service.yaml
    
  3. LoadBalancer: Exposes the service externally using a cloud provider’s load balancer.

    • Use Case: Production-grade external access to services.
    kubectl apply -f loadbalancer-service.yaml
    
  4. ExternalName: Maps a service to an external DNS name.

    • Use Case: Integrating with external services.
    kubectl apply -f externalname-service.yaml
    

Service Discovery Mechanisms

  1. DNS: Kubernetes DNS assigns a DNS name to each service.

    nslookup my-service.my-namespace.svc.cluster.local
    
  2. Environment Variables: Kubernetes sets environment variables for services at Pod startup.

    echo $MY_SERVICE_SERVICE_HOST
    

Service Networking and DNS

A Kubernetes service is exposed on a cluster-internal IP by default. You can access it using the Service’s DNS name:

  • <service-name>.<namespace>.svc.cluster.local

Load Balancing and Traffic Distribution

Kubernetes Service performs load balancing by distributing incoming network traffic across multiple Pods.

  • Round Robin
  • Session Affinity

Complete Exercise: Creating and Testing a ClusterIP Service

Setup

Create a Deployment for an Nginx server:

kubectl create deployment nginx-deployment --image=nginx

Steps

  1. Create a YAML file named clusterip-service.yaml:

    apiVersion: v1
    kind: Service
    metadata:
      name: my-clusterip-service
    spec:
      type: ClusterIP
      ports:
      - port: 80
        targetPort: 80
      selector:
        app: nginx
    
  2. Apply the ClusterIP service:

    kubectl apply -f clusterip-service.yaml
    
  3. Verify the service is running:

    kubectl get svc
    

Troubleshooting

  • Ensure your selectors match between the Service and the Deployment.

Solution

To test the service, exec into a Pod and perform a curl command:

kubectl exec -it <POD_NAME> -- curl my-clusterip-service

You should see the Nginx welcome page, confirming the ClusterIP service works.