从同样位于 boot2docker vm 内的 Docker 容器访问主机作为 localhost [英] Accessing host machine as localhost from a Docker container that's also inside a boot2docker vm
问题描述
假设我有一台服务器在 OSX 的 8000 端口上运行.我的 Docker 容器如何通过 localhost:8000
访问它?我也无法更改主机名,因为容器中的应用不在我的控制之下.
我已经阅读了之前关于使用 --net="host"
的容器访问主机网络的讨论.但是,我在 OSX 上并且 Docker 在 VM 内运行,因此 localhost 从带有 --net="host"
的 Docker 容器转到 VM 而不是我的真机.
然后我尝试了端口转发解决方法,如下所示:VBoxManage modifyvm "boot2docker-vm" --natpf1 "tcp-port8000,tcp,,8000,,8000";
无济于事.
任何建议将不胜感激.
感谢 palimpestor 的回答,我想通了:
代替 --net="host"
,使用 --add-host="localhost:10.0.2.2"
>
确实:
- 10.0.2.2 是为 NAT 模式下的访客网络接口定义的默认网关(参考).
阅读:这是你的主机,从 boot2docker 看到. --add-host...
正在/etc/hosts 中添加localhost 10.0.2.2
(reference)
注意:您需要在 boot2docker VM VirtualBox 设置中设置一个 NAT 适配器(我是通过 GUI 完成的,不知道 CLI).
Suppose I have a server running on port 8000 on OSX. How can my Docker container access it via localhost:8000
? I can't change the hostname too as the app in the container is not in my control.
I've read this previous discussion on using --net="host"
for a container to access the host machine's network. However, I'm on OSX and Docker runs inside a VM so localhost from the Docker container with --net="host"
goes to the VM and not my real machine.
Then I tried port forwarding workaround like so: VBoxManage modifyvm "boot2docker-vm" --natpf1 "tcp-port8000,tcp,,8000,,8000";
to no avail.
Any suggestion would be greatly appreciated.
Thanks to palimpestor's answer I figured it out:
Instead of --net="host"
, use --add-host="localhost:10.0.2.2"
Indeed:
- 10.0.2.2 is the default gateway defined for the guest network interface in NAT mode (reference).
Read: it's your host, seen from boot2docker. --add-host...
is addinglocalhost 10.0.2.2
in /etc/hosts (reference)
Note: you need to have set up a NAT adapter in your boot2docker VM VirtualBox settings (I did it through the GUI, don't know the CLI).
这篇关于从同样位于 boot2docker vm 内的 Docker 容器访问主机作为 localhost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!