[英]Why can't I access my service from my container host when running with `--network host` mode?
I have an application running as a container with an endpoint of http://localhost:8080/metrics . 我有一个应用程序作为容器运行,端点为http:// localhost:8080 / metrics 。
If I start my container with the following command, I can access the service from my container host: 如果使用以下命令启动容器,则可以从容器主机访问该服务:
docker run -p 8080:8080 prometheus/golang-example-random
However, in other containers on the same machine I have target endpoints of localhost:8080
, which doesn't work with this setup. 但是,在同一台计算机上的其他容器中,我具有localhost:8080
目标端点,该端点不适用于此设置。 So instead, I tried running with --network host
. 因此,我尝试使用--network host
运行。 However, when I run with this configuration: 但是,当我使用此配置运行时:
docker run --network host prometheus/golang-example-random
I can no longer access the service from my container host. 我无法再从容器主机访问该服务。 Am I missing something trivial here? 我在这里错过了一些琐碎的事情吗?
If you want your containers to be on the same network and be able to talk to each other, the best options is to create a docker network for them and then have them all join the same network. 如果您希望容器位于同一网络上并且能够互相通信,最好的选择是为它们创建一个docker网络 ,然后将它们全部加入同一网络。
So you can run: 这样就可以运行:
$ docker network create -d bridge [name]
Then instead of --network host you can pass --network [name]
to your docker run command. 然后,您可以将--network [name]
传递给--network [name]
run命令,而不是--network host。 You'd also need --name which is what you can then use to talk to that container from other containers on the same network: 您还需要--name,然后便可以使用--name从同一网络上的其他容器与该容器进行对话:
$ docker run --name goexample --network [name] -p 8080:8080 prometheus/golang-example-random
Now if you were to create another new container on that new custom docker network, you'd be able to talk to the above container using its name as a hostname, ie goexample:8080/metrics
. 现在,如果您要在该新的自定义docker网络上创建另一个新容器,则可以使用其名称作为主机名与上述容器进行对话,即goexample:8080/metrics
。
Because we're still also binding the golang-example's 8080 port to the host's 8080, you'd still be able to access localhost:8080/metrics
from the host. 由于我们仍将golang-example的8080端口绑定到主机的8080,因此您仍然可以从主机访问localhost:8080/metrics
。
However when you're running multiple containers, keep in mind that you can't bind them to the same host port . 但是,当您运行多个容器时,请记住不能将它们绑定到同一主机端口 。 Similarly if you are running all containers on the host network, then the services themselves can't all use 8080, for the same reason. 同样,如果您在主机网络上运行所有容器,则出于相同的原因,服务本身也不能全部使用8080。 In your case that is likely to be the problem. 在您的情况下,这很可能是问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.