在docker容器中访问宿主机端口

运行在 docker 容器中的一个项目需要访问宿主机的某个端口,也就是容器 A 中的项目访问宿主机项目 B。

之前是可以通过下边的方式正常访问的,最近不知道动了哪里突然出现 500 ,一番折腾,总算是解决了,这里记录一下,预防以后遇到同样问题。

正常的访问方式

在 A 的项目中以下边的地址来访问即可:

http://host.docker.internal

问题解决

重启电脑后,在容器中 ping 这个地址:

PING host.docker.internal (192.168.65.2) 56(84) bytes of data.
64 bytes from 192.168.65.2: icmp_seq=1 ttl=37 time=2.09 ms
64 bytes from 192.168.65.2: icmp_seq=2 ttl=37 time=1.05 ms
64 bytes from 192.168.65.2: icmp_seq=3 ttl=37 time=1.05 ms
64 bytes from 192.168.65.2: icmp_seq=4 ttl=37 time=1.16 ms
64 bytes from 192.168.65.2: icmp_seq=5 ttl=37 time=1.03 ms

可以看到实际访问的是 192.168.65.2 这个地址,那么打开宿主机的 host,果然没了! Σ( ° △ °|||)︴
加上一行:

192.168.65.2 host.docker.internal

再次访问,ok!

在容器内安装 ping

不指定用户进入容器,然后执行:

apt-get update
apt-get install iputils-ping

疑问

正常情况下,host 应该有 docker 自动添加的地址以供访问,但是我的不知道为什么没了。

后来创建了另一套新的容器以后看到 host 有以下新增的地址,所以我猜测这个应该是创建容器时会自动添加,不知道队不对,恳请知道的大佬解惑:


# Added by Docker Desktop
192.168.1.164 host.docker.internal
192.168.1.164 gateway.docker.internal
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section

原文地址:https://www.cnblogs.com/m-finder/p/11592716.html