Service discovery is the process of figuring out how to connect to a service. While there is a service discovery option based on environment variables available, the DNS-based service discovery is preferable. Note that DNS is a cluster add-on so make sure your Kubernetes distribution provides for one or install it yourself.

Let’s create a service named thesvc and an RC supervising some pods along with it:

$ kubectl create -f

$ kubectl create -f

Now we want to connect to the thesvc service from within the cluster, say, from another service. To simulate this, we create a jump pod in the same namespace (default, since we didn’t specify anything else):

$ kubectl create -f

The DNS add-on will make sure that our service thesvc is available via the FQDN thesvc.default.svc.cluster.local from other pods in the cluster. Let’s try it out:

$ kubectl exec jumpod -c shell -i -t -- ping thesvc.default.svc.cluster.local
PING thesvc.reshifter.svc.cluster.local ( 56(84) bytes of data.

The answer to the ping tells us that the service is available via the cluster IP We can directly connect to and consume the service (in the same namespace) like so:

 $ kubectl exec jumpod -c shell -i -t -- curl http://thesvc/info
{"host": "thesvc", "version": "0.5.0", "from": ""}

Note that the IP address above is the cluster-internal IP address of the jump pod.

To access a service that is deployed in a different namespace than the one you’re accessing it from, use a FQDN in the form $SVC.$NAMESPACE.svc.cluster.local.

Let’s see how that works by creating:

  1. a namespace other
  2. a service thesvc in namespace other
  3. an RC supervising the pods, also in namespace other

If you’re not familiar with namespaces, check out the namespace examples first.

$ kubectl create -f

$ kubectl create -f

$ kubectl create -f

We’re now in the position to consume the service thesvc in namespace other from the default namespace (again via the jump pod):

$ kubectl exec jumpod -c shell -i -t -- curl http://thesvc.other/info
{"host": "thesvc.other", "version": "0.5.0", "from": ""}

Summing up, DNS-based service discovery provides a flexible and generic way to connect to services across the cluster.