Search code examples
microservicesconsulservice-discovery

Services communication in consul


I am developing several services, and use consul as the service registry. I'm able to register all of my services to the consul.

And now for the next thing to do, I need to be able to communicate from service A to service B.

Without a service registry, usually what I did was simply dispatch a client HTTP request from service A to service B.

But since now I already have service discovery in place, should I get the service B host address via consul and then dispatch a client HTTP request to the service B host address something like that? Or does the consul also provide an API gateway, so I only need to dispatch my client HTTP request from service A to the consul, and then the consul will automatically forward it to the destination?

Also if there is relevant documentation about my case, I would be very glad to take a look at it? (I can't find the relevant documentation, probably my google search keyword is wrong)


Solution

  • Consul supports two methods for service discovery, DNS and HTTP.

    Applications can perform DNS lookups against their local Consul agent which exposes a DNS server on port 8600 (you can also configure DNS forwarding). For example, an application can issue an A record query for web.service.consul and Consul will return a list of healthy instance endpoints for the web service. SRV lookups are also supported in order to retrieve the IP and port for a given service. The DNS interface also supports querying endpoints by service tag and data center. Details can be found at Consul.io: DNS - Service Lookups.

    HTTP-based service discovery can be performed by querying the /v1/health/service/:name endpoint against the local agent. The following will return a full list of healthy and unhealthy endpoints for the service nginx.

    $ curl http://127.0.0.1:8500/v1/health/service/nginx
    

    You can use the passing query parameter to restrict the output to only healthy services.

    $ curl "http://127.0.0.1:8500/v1/health/service/nginx?passing"
    

    I recommend reviewing the guide Register a Service with Consul Service Discovery for more info on registering and querying services from the catalog.

    Lastly, API gateways like Traefik and Solo's Gloo support using Consul for service discovery (see Traefik's Consul Catalog Provider and Gloo's Consul Services). You could configure your services to route requests to these gateways, and allow the gateway to forward to the backend destination.