How does docker's `net=host` setting work, and

2019-02-08 01:45发布

Docker has a run option net=host documented here that allows you to run a virtual machine that shares the network stack with the host — for example, processes inside the docker container can connect to the host machine via localhost and vice versa.

I want to set up a Linux VM on Mac OS X that does the same thing; I've tried using Vagrant and its various networking settings without much luck.

Does Docker's VM rely on the host and guest OSes both being Linux, or is there some way to accomplish this OSX->Linux that I'm missing?

标签: macos docker
2条回答
叼着烟拽天下
2楼-- · 2019-02-08 02:25

Thanks to some help from my colleagues I found a solution to this problem. This solution works with boot2docker/VirtualBox. I just created my docker VM with boot2docker init, I didn't make any specific changes to the VM configuration.

First you run the docker image with --net=host, so that it shares the network with the host VM e.g.

docker run -it --net=host ubuntu bash

Then you need to find the IP address from the VM used for the docker containers, you can do this by running boot2docker ssh the OSX host. You can then find the IP address of the VM by finding its gateway:

$ netstat -rn | grep UG | awk '{print $2}'
10.0.2.2

So in my case it's 10.0.2.2. You can now access ports opened on the host, i.e. on a program running on OSX from your docker container by using this IP address.

To automate you could find the IP address first and then pass it into the docker command as an environment variable...

查看更多
Explosion°爆炸
3楼-- · 2019-02-08 02:26

I have found another answer that works, I'll share that here so that people can choose :)

First you need to figure out what the IP address of the preferred network interface is on your OSX host is. The following shell command did this for me:

echo "show State:/Network/Global/IPv4" | scutil | grep PrimaryInterface | awk '{print $3}' | xargs ifconfig | grep inet | grep -v inet6 | awk '{print $2}'

In my case this prints out: 10.226.98.247

Then you can simply use that address inside docker, or even better give this address a hostname for inside docker:

docker run -it --add-host dockerhost:10.226.98.247 ubuntu bash

Then you can use the same dockerhost hostname in your docker container regardless of what environment you're launching your container in...

查看更多
登录 后发表回答