運行在 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