Kubernetes Service Discovery

Kubernetes handles service discovery through a combination of DNS and environment variables. This allows applications running in a Kubernetes cluster to find and communicate with each other seamlessly.

1. DNS-Based Service Discovery

Kubernetes includes a built-in DNS server that automatically assigns DNS names to services. When a service is created, it gets a DNS entry that can be used by other pods to access it.

For example, if you create a service named my-service in the default namespace, it can be accessed using the DNS name my-service.default.svc.cluster.local.

apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- port: 80
targetPort: 8080

In a pod, you can access this service using:

curl http://my-service.default.svc.cluster.local

2. Environment Variables

When a pod is created, Kubernetes injects environment variables for each service that is available in the same namespace. These environment variables contain information about the service, such as its name, cluster IP, and ports.

For example, if you have a service named my-service, Kubernetes will create environment variables like:

  • MY_SERVICE_SERVICE_HOST: The IP address of the service.
  • MY_SERVICE_SERVICE_PORT: The port on which the service is exposed.

Here’s how you can access these environment variables in a pod:

echo $MY_SERVICE_SERVICE_HOST
echo $MY_SERVICE_SERVICE_PORT

3. Headless Services

In some cases, you may want to enable direct access to the individual pods rather than load balancing through a service. This can be achieved using a headless service. A headless service is created by setting the clusterIP field to None.

apiVersion: v1
kind: Service
metadata:
name: my-headless-service
spec:
clusterIP: None
selector:
app: my-app
ports:
- port: 80
targetPort: 8080

With a headless service, DNS queries will return the individual pod IPs instead of a single service IP, allowing for direct communication.

Conclusion

Kubernetes provides robust service discovery mechanisms through DNS and environment variables, making it easy for applications to find and communicate with each other. Understanding these mechanisms is essential for building scalable and resilient applications in a Kubernetes environment.