为什么启动docker容器会更改主机的默认路由?

时间:2016-12-11 09:34:10

标签: networking docker routing

我已使用以下路由表配置主机:

user@host:~ $ netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
{VPN SERVER IP} 192.168.2.1     255.255.255.255 UGH       0 0          0 wlan0
172.17.0.0      0.0.0.0         255.255.0.0     U         0 0          0 docker0
192.168.2.0     0.0.0.0         255.255.255.0   U         0 0          0 wlan0

因此,如果没有连接到VPN,我没有连接到互联网:

user@host:~ $ ping google.com
connect: Network is unreachable

一旦启动我的docker容器,主机的路由表就会变为:

user@host:~ $ netstat -rn
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.2.1     0.0.0.0         UG        0 0          0 wlan0
{VPN SERVER IP} 192.168.2.1     255.255.255.255 UGH       0 0          0 wlan0
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 docker0
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 vethcbeee28
172.17.0.0      0.0.0.0         255.255.0.0     U         0 0          0 docker0
192.168.2.0     0.0.0.0         255.255.255.0   U         0 0          0 wlan0

我再次连接到互联网:

user@host:~ $ ping google.com
PING google.com (216.58.212.238) 56(84) bytes of data.

基本上我的主机不应该能够连接到互联网而无需连接到VPN。但是,启动容器会再次设置到我的网关的默认路由。

有人知道这里发生了什么吗?而且,如何避免这种情况?

到目前为止,我找到了一个我想避免的解决方法here

修改

我发现即使从dockerfile构建图像也会发生这种情况!

2 个答案:

答案 0 :(得分:1)

您可以在nogateway文件中指定/etc/dhcpd.conf选项。

# Avoid to set the default routes.
nogateway

答案 1 :(得分:1)

我遇到了同样的问题,终于找到了解决方案:

# Stop and disable dhcpcd daemon on system boot since we going to start it manually with /etc/rc.local
# NB: we do so, cause 'docker' when building or running a container sets up a 'bridge' interface which interferes 'failover'
systemctl stop dhcpcd
systemctl disable dhcpcd

# Start dhcpcd daemon on each interface we are interested in
dhcpcd eth0
dhcpcd eth1
dhcpcd wlan0

# Start dhcpcd daemon on every reboot
sed -i -e 's/^exit 0$//g' /etc/rc.local
echo "dhcpcd eth0" >> /etc/rc.local
echo "dhcpcd eth1" >> /etc/rc.local
echo "dhcpcd wlan0" >> /etc/rc.local
echo "" >> /etc/rc.local
echo "exit 0" >> /etc/rc.local

我还为docker添加了dns服务器(可能是不必要的)

cat >> /etc/docker/daemon.json << EOF
{
    "dns": ["8.8.8.8", "8.8.4.4"]
}
EOF
service docker restart