Service Discovery

Let's see how Kubernetes implements Service discovery.

Kubernetes implements Service discovery in a couple of ways:

  • DNS (preferred)
  • Environment variables (definitely not preferred)

Method I: DNS

DNS-based Service discovery requires the DNS cluster-add-on – this is just a fancy name for the native Kubernetes DNS service. I can’t remember ever seeing a cluster without it, and if you followed the installation methods from the “Installing Kubernetes” chapter, you’ll already have this. Behind the scenes, it implements:

  • Control plane Pods running a DNS service
  • A Service object, called kube-dns that sits in front of the Pods
  • Kubelets program every container with the knowledge of the DNS (via /etc/resolv.conf)

The DNS add-on constantly watches the API server for new Services and automatically registers them in the DNS. This means every Service gets a DNS name that is resolvable across the entire cluster.

Method II: environment variables

The alternative form of service discovery is through environment variables. Every Pod gets a set of environment variables that resolve every Service currently on the cluster. However, this is an extremely limited fallback in case you’re not using DNS in your cluster.

A major problem with environment variables is that they’re only inserted into Pods when the Pod is initially created. This means that Pods have no way of learning about new Services added to the cluster after the Pod itself is created. This is far from ideal and a major reason why DNS is the preferred method. Another limitation can be in clusters with a lot of Services.

Get hands-on with 1200+ tech skills courses.