容器网络(八)macvlan 网络隔离和连通【52】

(十)macvlan 网络隔离和连通

上一节我们创建了两个 macvlan 并部署了容器,网络结构如下:

本节验证 macvlan 之间的连通性。

root@host1:~# docker exec bbox01 ping -c 2 172.16.10.11

root@host1:~# docker exec bbox02 ping -c 2 172.16.20.11
不通

bbox1 能 ping 通 bbox3,bbox2 能 ping 通 bbox4。即:同一 macvlan 网络能通信。

root@host1:~# docker exec bbox01 ping -c 2 172.16.10.10
PING 172.16.10.10 (172.16.10.10): 56 data bytes
64 bytes from 172.16.10.10: seq=0 ttl=64 time=0.059 ms
64 bytes from 172.16.10.10: seq=1 ttl=64 time=0.042 ms
root@host1:~# docker exec bbox02 ping -c 2 172.16.20.10
PING 172.16.20.10 (172.16.20.10): 56 data bytes
64 bytes from 172.16.20.10: seq=0 ttl=64 time=0.084 ms
64 bytes from 172.16.20.10: seq=1 ttl=64 time=0.061 ms

bbox1 无法 ping 通 bbox2 和 bbox4。即:不同 macvlan 网络之间不能通信。但更准确的说法应该是:不同 macvlan 网络不能 在二层上 通信。在三层上可以通过网关将 macvlan 连通,下面我们就启用网关。

我们会将 Host 10.0.0.20 配置成一个虚拟路由器,设置网关并转发 VLAN10 和 VLAN20 的流量。当然也可以使用物理路由器达到同样的效果。首先确保操作系统 IP Forwarding 已经启用。

cuiyongchao@cuiyongchao:~$ sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1
cuiyongchao@cuiyongchao:~$
输出为 1 则表示启用,如果为 0 可通过如下命令启用:

sysctl -w net.ipv4.ip_forward=1


在 /etc/network/interfaces 中配置 vlan sub-interface:

auto eth38
iface eth38 inet manual
auto eth38.10
iface eth38.10 inet manual
vlan-raw-device eth38
auto eth38.20
iface eth38.20 inet manual
vlan-raw-device eth38

启用 sub-interface:

ifconfig eth38.10

ifconfig eth38.20

将网关 IP 配置到 sub-interface:

ifconfig eth38.10 172.16.10.1 netmask 255.255.255.0 up

ifconfig eth38.20 172.16.20.1 netmask 255.255.255.0 up

添加 iptables 规则,转发不同 VLAN 的数据包。

iptables -t nat -A POSTROUTING -o eth38.10 -j MASQUERADE

iptables -t nat -A POSTROUTING -o eth38.20 -j MASQUERADE

iptables -A FORWARD -i eth38.10 -o eth38.20 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -i eth38.20 -o eth38.10 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -i eth38.10 -o eth38.20 -j ACCEPT

iptables -A FORWARD -i eth38.20 -o eth38.10 -j ACCEPT

现在 host1 上位于 mac_net10 的 bbox1 已经可以与 host2 上位于 mac_net20 的 bbox4 通信了。

下面我们分析数据包是如何从 bbox1(172.16.10.10)到达 bbox4(172.16.20.11)的。整个过程如下图所示:

原文地址:https://www.cnblogs.com/cuiyongchao007/p/14110137.html