Register service with Consul using Consul API

There are many ways to register a service with Consul such as using a configuration file, using Consul API, … In this tutorial, I will guide you how to use Consul API to register a service with Consul!

First, I will create a simple service with Spring Boot with Spring Web dependency:

expose a simple endpoint like “/hello”:

Run this Spring Boot application and request to http://localhost:8080/hello, you will see the following result:

Now, let’s register this service with Consul!

To register a service with Consul, you can use the Register Service API at https://developer.hashicorp.com/consul/api-docs/agent/service#register-service. Basically, you can request with the PUT method to Consul’s address http://localhost:8500/v1/agent/service/register with data in the request body, for my example, as follows:

  • Name is the name of the service
  • Address is the hostname of the service. Here, I ran Consul using Docker Compose, and my service is running on the host machine, so as you can see, the address information will be host.docker.internal.
  • Port is the port where the service is running

For my example, I only declare some basic information as above. Depending on the case, please see more data requests that Consul supports in the link above!

The result when I run the above request with Postman is as follows:

Now, check the services in Consul UI, you can see the result as follows:

So, we have successfully registered a simple service with the Consul API!

Add Comment