Service discovery

Microservices · lesson 6 of 33 · 3 min read

Find healthy instances by name instead of hard-coding IPs that go stale on every deploy.

Open this lesson in the learning hub

Key points

  • Instances come and go with scaling, restarts and rescheduling. Hard-coded IPs are wrong within minutes.
  • Server-side discovery: call a stable name, something else picks the instance. A Kubernetes Service plus DNS does this.
  • Client-side discovery: the caller asks a registry (Eureka, Consul) for instances and balances itself, e.g. Spring Cloud LoadBalancer.
  • Discovery is only as good as your health checks. Expose /actuator/health/readiness so dead instances leave the rotation.
  • Spring Boot enables the liveness and readiness health groups automatically when it detects it is running on Kubernetes.
  • On Kubernetes you usually do not need Eureka at all. DNS plus readiness probes covers most cases.

Example

apiVersion: v1
kind: Service
metadata:
  name: inventory              # other services just call http://inventory
spec:
  selector:
    app: inventory
  ports:
    - port: 80
      targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: inventory
spec:
  replicas: 3
  selector:
    matchLabels:
      app: inventory
  template:
    metadata:
      labels:
        app: inventory
    spec:
      containers:
        - name: app
          image: registry.example.com/inventory:1.4.2
          ports:
            - containerPort: 8080
          readinessProbe:      # fails -> pod removed from the Service
            httpGet:
              path: /actuator/health/readiness
              port: 8080
            periodSeconds: 5

Call names, not addresses, and let health checks decide who answers.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Microservices course, and every lesson in it is listed on the Microservices contents page.