What is service discovery in Kubernetes?

Service discovery in Kubernetes is the mechanism by which services within a Kubernetes cluster can dynamically find and communicate with each other. Kubernetes uses DNS (Domain Name System) for service discovery, where each service gets a DNS name that other services can use to reach it. This allows for decoupling between services, as they don’t need to know each other’s IP addresses or locations directly.

We can implement service discovery in Kubernetes with the help of a YAML file by following the steps below:

Initialize the YAML file

To start off, we’ll specify the Kubernetes API version being used and the type of Kubernetes resource that we want to use:

apiVersion: v1
kind: Service

Here, the v1 API version is used with the Service resource type.

Define metadata

Next, we’ll define the metadata about the service, including its name:

metadata:
name: my-service

For this example, we’ll use the name my-service as part of the metadata for our service example.

Define the service specifications

Now, we move on to the crucial step in service discovery: defining the service's specifications.

spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080

This includes specifying the labels of the pods that this service should route traffic under the selector tag, with the label app: my-app. In addition, we will specify the ports that the service will listen on under the ports tag, which consists of the protocol equal to TCP, the port equal to 80 and targetPort equal to 8080 (the port on the pods to which traffic will be forwarded).

Code

The YAML file implementing all of these steps can be tested below. Click the "Run" button to see the service discovery in action.

apiVersion: v1
kind: Service
metadata:
  name: startup
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
Service discovery in Kubernetes

Conclusion

In conclusion, service discovery in Kubernetes is crucial for facilitating communication between different components within a cluster. By abstracting away the specifics of IP addresses and locations, Kubernetes enables services to dynamically discover and interact with each other using DNS names, such as with the DNS name my-service, as seen in this example.

Unlock your potential: Kubernetes Deployment and Advanced Operations series, all in one place!

To deepen your understanding of Kubernetes deployment and management, explore our series of Answers below:

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved