Linux-veth 虚拟网络设备小实验

122 阅读1分钟

Linux 使用veth 从主机的其他网络命名空间 与 外部网络进行通信

需求:

     实现 从Linux 的一个网络命名空间之中 与 外部网络建立联系。

目的:模拟docker的网络通信。

实验步骤:

1: 创建一对 veth pair 设备

       ip link add veth0 type veth peer name veth1

2: 创建一个命名空间ns1

       ip netns add ns1

3: 将 veth0 放入ns1 网络命名空间之中

       ip link set veth1 netns ns1

4: 设置 veth0的ip地址,并启用


     ip netns exec ns1 ip addr add 192.168.24.10/24 dev veth1

     ip netns exec ns1 ip link set veth1 up

     ip link set veth0 up

5: 设置ns1网络空间之中的默认路由

     ip netns exec ns1 ip route add 0.0.0.0/0 via 172.16.217.154 dev veth1 onlink

6: 增加转发规则 以及 SNAT 规则


      iptables -A FORWARD -i veth0 -o eth0  -j ACCEPT

      iptables -A FORWARD -i eth0  -o veth0 -j ACCEPT

     iptables -t nat -A POSTROUTING -s 192.168.24.10 -j MASQUERADE

7:进入网络命名空间 向百度 发送ping 

    ip netns exec ns1 ping www.baidu.com