在 docker 容器中使用 host.docker.internal 拒绝连接

Leo*_* Ma 6 networking dns bash ubuntu docker

localhost:8000在主机上有一个打开的。具体来说:

$ php -S localhost:8000
PHP 7.1.19 Development Server started at Tue Jul 16 09:49:08 2019
Listening on http://localhost:8000
Run Code Online (Sandbox Code Playgroud)

我可以在主机上执行curl -i http://localhost:8000以获得响应,我也可以通过主机浏览器访问它,完全没有问题。

但是,当我尝试访问 Mac 上 docker 容器上的主机时,连接被拒绝:

$ curl -i http://host.docker.internal:8000
curl: (7) Failed to connect to host.docker.internal port 8000: Connection refused

$ telnet host.docker.internal 8000
Trying 192.168.65.2...
telnet: Unable to connect to remote host: Connection refused
Run Code Online (Sandbox Code Playgroud)

host.docker.internal从命令中可以看出,docker 容器可以解析 DNS telnet,我也可以ping,但连接被拒绝。

$ ping host.docker.internal
PING host.docker.internal (192.168.65.2) 56(84) bytes of data.
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=1 ttl=37 time=0.186 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=2 ttl=37 time=0.463 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=3 ttl=37 time=0.420 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=4 ttl=37 time=0.428 ms
64 bytes from 192.168.65.2 (192.168.65.2): icmp_seq=5 ttl=37 time=0.722 ms
Run Code Online (Sandbox Code Playgroud)

更新

我发现了这个GitHub 问题评论,不知道这是否有帮助。

小智 1

我能够让它发挥作用。我不确定您是否仍然面临这个问题,我的解决方案是否适合您。但是,尝试一下总没有坏处。

我注意到没有映射/绑定到主机的端口的容器存在识别host.docker.internal主机的localhost. 因此,我为有连接问题的容器使用了一个虚拟端口,并且它开始工作。

希望这可以帮助。