容器里怎么访问 Mac 上跑的服务?host.docker.internal 是什么、解析到哪里、对只监听 127.0.0.1 的服务有用吗?这篇逐项实测,包括 --add-host host-gateway 的写法。
nslookup host.docker.internal:退出码 0;地址 ['<本机局域网IP>:53', '<本机局域网IP>', 'fdc4:f303:9324::254'] nslookup gateway.docker.internal:退出码 0;地址 ['<本机局域网IP>:53', 'fdc4:f303:9324::1', '<本机局域网IP>'] nslookup kubernetes.docker.internal:退出码 0;地址 ['<本机局域网IP>:53', 'fdc4:f303:9324::7', '<本机局域网IP>'] nslookup no.such.name.internal:退出码 1;地址 ['<本机局域网IP>:53'] 容器里的 /etc/hosts 有 host.docker.internal 吗?0 行
host.docker.internal 由 Docker Desktop 的 DNS 解析(192.168.65.254 和一个 IPv6 地址),容器的 /etc/hosts 里并没有。gateway.docker.internal、kubernetes.docker.internal 同理(后者我没有深究)。
Mac 上监听 127.0.0.1:9840 的服务:容器访问 host.docker.internal:9840 → hello from the Mac Mac 上监听 0.0.0.0:9850 的服务:容器访问 host.docker.internal:9850 → hello from the Mac 容器访问 127.0.0.1:9840(容器自己的回环)→ wget: can't connect to remote host (127.0.0.1): Connection refused 自定义网络里的容器访问 host.docker.internal:9840 → hello from the Mac
Mac 上只监听 127.0.0.1 的 HTTP 服务,容器访问 host.docker.internal 的端口成功——按我的推断是被 Docker Desktop 转发到 Mac 本机的。容器里的 127.0.0.1 指的是容器自己,所以会被拒绝。
加 --add-host host.docker.internal:host-gateway 后 /etc/hosts 里:<本机局域网IP> host.docker.internal fdc4:f303:9324::254 host.docker.internal 这时访问 host.docker.internal:9840 → hello from the Mac
--add-host host.docker.internal:host-gateway 把 192.168.65.254 等地址写进 /etc/hosts。在 Docker Desktop 上不加也能解析,它主要用于没有预置这个名字的 Linux 宿主机,我没有在 Linux 上验证。
--network host 的容器访问 host.docker.internal:9840 → hello from the Mac
--network host 的容器同样能访问。