Reputation: 15844
I have two SpringBoot
microservices M1
(port 2002) and M2
(port 2004)
M1
and M2
are communicating successfully if I run them using eclipse
(run as Java Project or SpringBoot Project).
However, I want to communicate them using Docker container
.
So I build images for both Microservices
(M1
and M2
) using the command:
docker build -f Dockerfile -t image_name .
And run the images using:
docker run -p 2004:2004 image_name
Note: I am exposing same port from docker as defined above
But the M1 and M2 are not able to communicate.
I am using RestTemplate
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Boolean> isUp = restTemplate.getForEntity("http://localhost:2002/apis/test",Boolean.class);
I am getting below exception :
I/O error on GET request for \"http://localhost:2002/apis/test\": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
However, If I call the other microservice using my machine's IP, It's communicating successfully
ResponseEntity<Boolean> isUp = restTemplate.getForEntity("http://XX.XX.XX.XXX:2002/apis/test",Boolean.class);
Can someone please tell if I am doing it write(using IP address) or there is another good approach to call one microservice from another using Docker?
Upvotes: 5
Views: 10205
Reputation: 1592
Alternately, you can also link the two containers together by --link
. Assuming you want container1 as client to container2, you can use below:
sudo docker run --link container2 --name=container1 -d image_name
Upvotes: 3
Reputation: 4351
Trying to communicate with the other container won't work with localhost
.
You should create a custom bridged network, which will allow you to refer to the containers by name. And there is no need to publish the ports if you are only talking internally.
# create network
docker network create -d bridge mynet
# container 1
docker container run --network mynet --name container1 -d image_name
# container 2
docker container run --network mynet --name container2 -d some_other_image_name
The IP in code snippet can then be replaced with the name of the other container
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Boolean> isUp = restTemplate.getForEntity("http://container2:2002/apis/test",Boolean.class)
Upvotes: 6