问题描述
现在如何工作:
Microservice X使用静态ip向Microservice Y发出REST API请求
Microservice X makes REST API request to Microservice Y with static ip
http://{ip-address}:{port}/doSomething
问题:
问题是我不能再保证静态IP.我不想使用docker主机名来解决这个问题:
The problem is that I can no long guarantee that static ip.I wan't to solve this by using the docker hostname instead:
http://hostname:{port}/doSomething
我尝试通过在docker-compose中创建使用的定义网络来实现这一目标:
I tried achieving this by creating a used defined network in docker-compose:
#part of docker-compose file
streamapp:
hostname: twitterstreamapp
image: twitterstreamapp
container_name: twitterstreamapp
restart: always
ports:
- '8090:8080'
build:
context: ./TwitterStream
dockerfile: Dockerfile
storeapp:
hostname: twitterstoreapp
image: twitterstoreapp
container_name: twitterstoreapp
restart: always
ports:
- '8095:8080'
build:
context: ./TwitterStore
dockerfile: Dockerfile
depends_on:
- 'mysql-db'
networks:
- backend
volumes:
MyDataVolume:
networks:
backend:
driver: bridge
我可以从容器X到容器Y进行ping操作.例如,不能卷曲.我该如何解决这个问题,或者这不是实现我想要的最佳方法.
I can ping from Container X to Container Y. But not Curl for example.How can I fix this, or is this not the best way to achieve what I want.
推荐答案
解决方案非常简单,您可以使用服务名称来代替IP或主机名.
The solution is very simple, instead of using IPs or Hostnames you can use the service's name.
在您的示例中,在streamapp
服务中,您可以使用http://storeapp:8080
访问其他服务.
In your example, in the streamapp
service you can access the other by using http://storeapp:8080
.
类似地,在storeapp
服务中,您可以在http://streamapp:8080
处访问另一个.
Similar, in the storeapp
service you can access the other at http://streamapp:8080
.
请不要使用内部端口,而不要使用导出的端口.
Please not that you must use the internal ports, not the exported ones.
当您从其他机器(即从互联网)访问服务时,此方法不适用.在这种情况下,您必须使用http://{IP_OF_THE_MACHINE}:8090
This does not apply when you access the service from the other machines, i.e. from the internet. In that case you must use the form http://{IP_OF_THE_MACHINE}:8090
这篇关于通过Docker主机名在两个微服务之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!