# docker 的网络隔离
## 做个模拟
1. 建一个bridge,一对veth,一个network namespace。
~~~
brctl addbr br0
ip link add vn1_0 type veth peer name vn1_1
ip netns add ns1
~~~
2. bridge配ip,`vn1_1`放到 ns1,`vn1_0`进br0。
~~~
ifconfig br0 172.20.100.1 netmask 255.255.0.0
ip link set vn1_1 netns ns1
brctl addif br0 vn1_0
# !!!!
ifconfig vn1_0 up
~~~
3. 在ns1里配网络,ping
~~~
ip netns exec ns1 bash
ifconfig vn1_1 172.20.100.120 netmask 255.255.0.0 up
route add default gw 172.20.100.1
ping 10.0.2.2
~~~
ping 不通host的网管,需要iptables 出马
~~~
root@debian:~# tcpdump -i br0 icmp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on br0, link-type EN10MB (Ethernet), capture size 262144 bytes
19:58:46.834606 IP 172.20.100.120 > 10.0.2.2: ICMP echo request, id 2000, seq 17, length 64
19:58:47.858865 IP 172.20.100.120 > 10.0.2.2: ICMP echo request, id 2000, seq 18, length 64
19:58:48.882416 IP 172.20.100.120 > 10.0.2.2: ICMP echo request, id 2000, seq 19, length 64
19:58:49.906566 IP 172.20.100.120 > 10.0.2.2: ICMP echo request, id 2000, seq 20, length 64
19:58:50.931042 IP 172.20.100.120 > 10.0.2.2: ICMP echo request, id 2000, seq 21, length 64
~~~
## iptables 出马
加入SNAT的规则,可以上网了
~~~
iptables -P FORWARD ACCEPT
iptables -F
iptables -F -t nat
iptables -t nat -A POSTROUTING -s 172.20.100.1/16 -o enp0s3 -j MASQUERADE
~~~
两个interface抓到的包:
~~~
root@debian:~# tcpdump -i enp0s3 icmp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
20:08:07.634320 IP 10.0.2.15 > iptq23f7c6dtetx: ICMP echo request, id 2143, seq 44, length 64
20:08:07.635684 IP iptq23f7c6dtetx > 10.0.2.15: ICMP echo reply, id 2143, seq 44, length 64
20:08:08.635845 IP 10.0.2.15 > iptq23f7c6dtetx: ICMP echo request, id 2143, seq 45, length 64
20:08:08.638997 IP iptq23f7c6dtetx > 10.0.2.15: ICMP echo reply, id 2143, seq 45, length 64
20:08:09.637640 IP 10.0.2.15 > iptq23f7c6dtetx: ICMP echo request, id 2143, seq 46, length 64
root@debian:~# tcpdump -i br0 icmp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on br0, link-type EN10MB (Ethernet), capture size 262144 bytes
20:08:14.646725 IP 172.20.100.120 > iptq23f7c6dtetx: ICMP echo request, id 2143, seq 51, length 64
20:08:14.649069 IP iptq23f7c6dtetx > 172.20.100.120: ICMP echo reply, id 2143, seq 51, length 64
20:08:15.648926 IP 172.20.100.120 > iptq23f7c6dtetx: ICMP echo request, id 2143, seq 52, length 64
20:08:15.650896 IP iptq23f7c6dtetx > 172.20.100.120: ICMP echo reply, id 2143, seq 52, length 64
~~~
## docker 里 ip netns show 的问题
主机上看不到 docker 网络的namespace,文件没放对位置
~~~
docker commit -m "test" -a "aa" 6129201c8f6a testimg
docker run -it testimg /bin/bash
docker ps
pid=`docker inspect --format='{{.State.Pid}}' 59fa1429e5d3`
root@debian:~# mkdir /var/run/netns/
root@debian:~# ln -sf /proc/$pid/ns/net /var/run/netns/
root@debian:~# ip netns show
net
~~~