We will be running in a dockerized environment, so having consul configured at “localhost” is no longer valid. We will be using the DOCKER_HOST_IP in the consul.yml file. On my local computer, the IP is 192.168.1.144. You can use ifconfig on Linux to find out your local IP.
When starting the docker-compose for services, we need to set up the DOCKER_HOST_IP as an environment variable to pass it into the container. For more info on how to set up the DOCKER_HOST_IP, please refer to docker host ip.
In consul.yml, change the consulUrl to use the host IP instead of localhost as localhost inside a container is the container loopback address and it cannot go outside of the container.
The Dockerfile generated from light-codegen should be available like this.
FROM openjdk:11.0.3-slimADD /target/aa-1.0.0.jar server.jarCMD["/bin/sh","-c","java -Dlight-4j-config-dir=/config -Dlogback.configurationFile=/config/logback.xml -jar /server.jar"]
Let’s build and tag a docker image for this service:
Now that we have all four API built and dockerized, let’s start the docker-compose.
Before we start the new docker-compose, make sure you stop the current consul docker container.
Start Consul using docker-compose:
git clone https://github.com/networknt/light-docker.git
docker-compose -f docker-compose-consul.yml up -d
Start APIs once Consul is ready from the light-docker folder.
docker-compose -f docker-compose-discovery.yml up -d
Now you can go to the Consul Web UI to check if all APIs are registered.
curl -k https://localhost:7441/v1/data
And here is the result.
["API D: Message 1 from port 7444","API D: Message 2 from port 7444","API B: Message 1","API B: Message 2","API C: Message 1","API C: Message 2","API A: Message 1","API A: Message 2"]
In this step, we have dockerized all APIs and start them together. We also, start Consul with separate compose first to allow all services to register them to the Consul server. To make it simple, we are using HTTP to connect to the Consul and still using the static port in the server.yml config file. If you want to learn production like docker-compose and Consul integration please take a look at Docker compose and Consul production.
In the next step, we are going to deploy all services to Kubernetes cluster instead of docker-compose.