Shashank
Shashank

Reputation: 782

Call a rest api from one pod to another pod in same kubernetes cluster

In my k8s cluster I have two pods podA and podB. Both are in same k8s cluster. Microservice on pod B is a spring boot rest api. Microservice on pod A have ip and port of pod B in its application.yaml. now every time when podB recreates, ip change which forces us to change ip in application.yml of podA. Please suggest a better way.

My limitation is : I can't change the code of podA.

Upvotes: 3

Views: 7841

Answers (2)

Matt
Matt

Reputation: 74879

A Service will provide a consistent DNS name for accessing Pods.

An application should never address a Pod directly unless you have a specific reason to (custom load balancing is one I can think of, or StatefulSets where pods have an identity).

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376

You will then have a consistent DNS name to access any Pods that match the selector:

my-service.default.svc.cluster.local

Upvotes: 10

Federkun
Federkun

Reputation: 36989

That's what service are for. Take a postgres service:

kind: Service
apiVersion: v1
metadata:
  name: postgres-service
spec:
  type: ClusterIP
  selector:
    app: postgres
  ports:
    - protocol: TCP
      port: 5432
      targetPort: 5432

You can use postgres-service in other pods instead of referring to the ip address of the pod. You also have the advantage that k8s's doing some load balancing for you as well.

Upvotes: 2

Related Questions