Linux Tunnel -- ipip

查看IP隧道相关操作

1
ip tunnel help

Linux原生L3隧道支持

ipip: IPv4 in IPv4

GRE: Generic Routing Encapsulation

sit: IPv6 over IPv4

ISATAP: Intra-Site Automatic Tunnel Addressing Protocol, IPv6

VTI: Virtual Tunnel Interface

容器构建ipip隧道

加载ipip模块

1
2
3
4
5
$ modprobe ipip
$ lsmod | grep ipip
ipip 16384 0
tunnel4 16384 1 ipip
ip_tunnel 28672 1 ipip

打开Ipv4转发功能

1
2
3
$ echo 1 > /proc/sys/net/ipv4/ip_forward
$ cat /proc/sys/net/ipv4/ip_forward
1

启动特权CentOS容器

1
$ docker run -it --privileged=true centos bash

安装网络工具组件

1
$ yum -y install net-tools

构建net namesapce、veth pair以及相关IP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ ip netns add ns1
$ ip netns add ns2
$ ip link add v1 type veth peer name v1_p
$ ip link add v2 type veth peer name v2_p

$ ip link set v1 netns ns1
$ ip link set v2 netns ns2

$ ip addr add 10.10.10.1/24 dev v1_p
$ ip link set v1_p up
$ ip addr add 10.10.20.1/24 dev v2_p
$ ip link set v2_p up

$ ip netns exec ns1 ip addr add 10.10.10.2/24 dev v1
$ ip netns exec ns1 ip link set v1 up
$ ip netns exec ns2 ip addr add 10.10.20.2/24 dev v2
$ ip netns exec ns2 ip link set v2 up

这时,使用v1 ping v2还不通。查看ns1路由表,发现缺少10.10.20.0/24网段的路由。ns2的路由表同理。

1
2
3
4
5
6
7
8
$ ip netns exec ns1 route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
10.10.10.0 0.0.0.0 255.255.255.0 U 0 0 0 v1
$ ip netns exec ns2 route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
10.10.20.0 0.0.0.0 255.255.255.0 U 0 0 0 v2

配置相关路由,再使用v1 ping v2,通!

1
2
3
4
5
6
7
8
9
$ ip netns exec ns1 route add -net 10.10.20.0 netmask 255.255.255.0 gw 10.10.10.1
$ ip netns exec ns2 route add -net 10.10.10.0 netmask 255.255.255.0 gw 10.10.20.1
$ ip netns exec ns1 ping -c 1 -I v1 10.10.20.2
PING 10.10.20.2 (10.10.20.2) from 10.10.10.2 v1: 56(84) bytes of data.
64 bytes from 10.10.20.2: icmp_seq=1 ttl=63 time=0.018 ms

--- 10.10.20.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.018/0.018/0.018/0.000 ms

配置ipip隧道,以及隧道内外层ip

1
2
3
4
5
6
7
$ ip netns exec ns1 ip tunnel add tun1 mode ipip remote 10.10.20.2 local 10.10.10.2
$ ip netns exec ns1 ip link set tun1 up
$ ip netns exec ns1 ip addr add 10.10.100.10 peer 10.10.200.10 dev tun1

$ ip netns exec ns2 ip tunnel add tun2 mode ipip remote 10.10.10.2 local 10.10.20.2
$ ip netns exec ns2 ip link set tun2 up
$ ip netns exec ns2 ip addr add 10.10.200.10 peer 10.10.100.10 dev tun2

使用隧道进行通信

1
2
3
4
5
6
7
$ ip netns exec ns1 ping -c 1 -I tun1 10.10.200.10 
PING 10.10.200.10 (10.10.200.10) from 10.10.100.10 tun1: 56(84) bytes of data.
64 bytes from 10.10.200.10: icmp_seq=1 ttl=64 time=0.040 ms

--- 10.10.200.10 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.040/0.040/0.040/0.000 ms

参考

《Kubernetes网络权威指南》