[英]curl localhost to connect from one docker container to another docker container
我有以下docker-compose
并在本地运行:
version: '3.4'
services:
testservice.api:
image: testservice.api
build:
context: .
dockerfile: Services/.../Dockerfile
ports:
- "5101:80"
sql.data:
image: postgres.jchem
build:
context: ../db/postgres
dockerfile: Dockerfile
ports:
- "5432:5432"
- "9090:9090"
现在在sql.data
容器中我尝试执行curl http://localhost:5101/...
但我得到退出代码(7)连接失败
当我尝试通过curl http://testservice.api/...
它可以工作。
为什么我不能连接localhost:port
? 如何通过curl localhost:port
实现从docker容器到另一个容器的curl localhost:port
?
为什么我不能连接localhost:port?
那是因为每个容器都有自己的网络接口,因此它自己的'localhost'。
如何通过curl localhost:port实现从docker容器到另一个容器的连接?
你可以做的是在每个组合服务中使用network_mode: "host"
,这样每个容器都使用相同的主机网络接口。 不过,我建议您调整您的应用程序以使其可配置,以便将其服务依赖关系URL作为参数(例如)。
当你在容器内部说localhost时,它将读作容器本身。 使容器能够与其他容器通信。 您需要确保这些容器连接在同一网络上,然后您可以尝试通过其DNS(其服务名称)或其容器IP访问它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.