
我的嘗試是仿照本教程。
如果實體介面未指派給網橋,我可以從命名空間 ping 到網路。
# Create namespace
ip netns add namespace1
# Create veth pair.
ip link add veth1 type veth peer name br-veth1
# Associate the non `br-` side with the namespace.
ip link set veth1 netns namespace1
# Give namespace-side veth ip addresses.
ip netns exec namespace1 ip addr add 192.168.1.11/24 dev veth1
# Create a bridge device naming it `br1` and set it up.
ip link add name br1 type bridge
# Turn up the bridge.
ip link set br1 up
# Set the bridge veth from the default namespace up.
ip link set br-veth1 up
# Set the veth from the namespace up too.
ip netns exec namespace1 ip link set veth1 up
# Add the br-veth1 interface to the bridge by setting the bridge device as their master.
ip link set br-veth1 master br1
# Add the physical interface to the bridge
ip link set enp3s0 master br1
# Set the address of the `br1` interface (bridge device) to 192.168.1.10/24 and also set the broadcast address to 192.168.1.255 (the `+` symbol sets the host bits to 255).
ip addr add 192.168.1.10/24 brd + dev br1
# add the default gateway in all the network namespace.
ip netns exec namespace1 ip route add default via 192.168.1.10
# Set us up to have responses from the network.
# -t specifies the table to which the commands should be directed to. By default, it's `filter`.
# -A specifies that we're appending a rule to the chain that we tell the name after it.
# -s specifies a source address (with a mask in this case).
# -j specifies the target to jump to (what action to take).
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j MASQUERADE
sysctl -w net.ipv4.ip_forward=1
答案1
不要使用veth+bridge!使用macvlan!
我最近和你一樣在veth+bridge上苦苦掙扎,幸運的是我發現了這個連結今晚,上面寫著:
在 MACVLAN 出現之前,如果您想從虛擬機器或命名空間連接到實體網絡,則需要建立 TAP/VETH 設備並將一側連接到網橋,同時將實體介面連接到主機上的網橋,如下圖所示。
現在,借助 MACVLAN,您可以將與 MACVLAN 關聯的實體介面直接綁定到命名空間,而無需橋接。
這就是我所做的:
$ sudo ip netns add ns0
$ sudo ip netns exec ns0 ip link set lo up
$ sudo ip link add macvlan0 link eth0 type macvlan mode bridge
$ sudo ip link set macvlan0 netns ns0
$ sudo ip netns exec ns0 ip link set macvlan0 up
$ sudo ip netns exec ns0 ip addr add 172.29.6.123/21 dev macvlan0
$ sudo ip netns exec ns0 ping 172.29.0.1
PING 172.29.0.1 (172.29.0.1) 56(84) bytes of data.
64 bytes from 172.29.0.1: icmp_seq=1 ttl=64 time=0.360 ms
64 bytes from 172.29.0.1: icmp_seq=2 ttl=64 time=0.412 ms
這是工作!
答案2
一切看起來都很好,直到最後兩個命令(網路命名空間中的預設閘道+主命名空間中的偽裝)。
如果跳過這兩個,您應該有一個配置,其中物理接口橋接到兩個內部接口,一個是192.168.1.10
主命名空間中橋的內部接口,另一個是192.168.1.11
in namespace1
。
因此,這與將兩個實體網路介面連接到同一子網路的方式相同,一個來自主命名空間,一個來自namespace
. (您可以使用 amacvlan
而不是 veth-pair來達到相同的效果)。
192.168.1.10
轉送和偽裝都不是必要的,從主命名空間進入的預設路由是錯誤的。
如果兩個命名空間的路由都是正確的(驗證這一點),您應該能夠 ping 通另一個接口,以及連接到實體接口的任何接口。
為了進行測試,我建議在;中啟動一個xterm
etc.namespace1
然後您可以直接配置所有內容,而無需一直鍵入ip netns exec namespace1 ip ...
。