httpkubernetesnestjsmicroservicesservice-discovery

NestJS - communication between micro-services using service discovery


I have 2 dockerized NestJS apps that need to communicate with one another using HTTP protocol.

One way is to use HttpModule to send http requests to the remote microservice. But with this the app needs to be aware of IP (exact urls) of the remote microservice.

  1. So I wanted to use some service discovery solution - kubernetes has built in service discovery mechanism but could not find many examples on how to achieve this with kubernetes.
  2. Then I found about client proxy in nestjs that can be use to refer to remote service using its name ?
  3. Can we use ClientProxy for http cases. Also I think its kind of confusing that NestJS docs says In Nest, a microservice is fundamentally an application that uses a different transport layer than HTTP. HTTP is an application layer protocol that uses TCP as Layer 4 protocol.

Solution

  • Looks like making it too complicated. Think Kubernetes think easy..!

    You can directly sue the service name in each other to connect the two micro services. Although service discovery is a good option to implement when you can tons of micro services.

    if you have only two micro services deployment with name service-1 & service-2 you can both connect to each other over this name. http://service-1 is and http://service-2

    service-1.yaml

    apiVersion: v1
    kind: Service
    metadata:
      name: service-1
    spec:
      type: clusterip
      selector:
        app: MyApp
      ports:
        - port: 80
          targetPort: 80
    

    If you don't want to go with a third party to implement the service discovery you can also leverage the Nginx.

    You can read my article : https://medium.com/@harsh.manvar111/service-discovery-with-nginx-kubernetes-999c692cd851

    All services connect to each other across Kubernetes cluster with service name.

    This is the FQDN : <service-name>.<namespace-name>.svc.cluster.local

    You can also use this with Kubernetes DNS will also resolve IP even if get changed anytime nothing to worry: http://<service-name>.<namespace-name>.svc.cluster.local

    For where is easy to understand my Keycloak application here trying to connect to Postgres database. Both running in same namespace.

    So keycloak connecting to Postgres database with service name only directly. Here Postgres service.yaml for ref.