为什么会有这么扭曲的需求呢?因为我决定把家里的主路由移到 docker 中的软路由里,让 NAS 作为单臂路由。
写在前面: 1. 本教程不会教学如何使你的 docker 容器连上macvlan
网络。 2. 本教程仅适用于 Linux。(由于3. 本教程假设你的宿主机的 interface 为macvlan
也仅在 Linux 上可用,所以其他系统还是绕道吧)eth0
,所在网段为10.0.0.0/24
,容器获得的IP为10.0.0.100
,如果你的配置和我的不一致,请作出相应修改。
Docker 的 macvlan
网络有一个特点,即使它让你的容器「显得像是」直接连接在你的物理网络上的一个物理机器一样,但是宿主机却无法和容器直接通过本地的网络地址通信。
正如这里所提到的那样:
Note: In Macvlan you are not able to ping or communicate with the default namespace IP address. For example, if you create a container and try to ping the Docker host’s eth0
it will not work. That traffic is explicitly filtered by the kernel modules themselves to offer additional provider isolation and security.
可是做单臂路由导致宿主没法通过“理应是”的新路由联网算是怎么回事啊!(恼
所以我们要来动一点歪脑筋:
# Run those commands on host.
ip link add bridger link eth0 type macvlan mode bridge
# Add a new macvlan interface running at bridge mode. Don't name it identical to your prior macvlan interface.(It's named bridger in this example)
ip addr add 10.0.0.101 dev bridger
# Assign an IP address to this interface.Make sure it is free at the time.(In this case, we are setting it to 10.0.0.101)
ip link set bridger up
# Enable it.
ip route add 10.0.0.100 dev bridger
# Modify the router so that the communication between host and 10.0.0.100 is made possible by bridger.
Tada! 试试在宿主机 ping 10.0.0.100
,是不是可以 ping 通了?
最后一点点是,重启之后这里的 bridger
会消失。所以我把这些东西放到了 rc.local
里。你也可以用喜欢的办法让它开机自动运行。