Chapter 1 Deep leaning of docker

1. Vethpair 简单实验——实现两个命名空间互联

创建veth-pair

ip netns add charles-netns

ip link add veth0 type veth peer name veth1

ip link set veth1 netns charles-netns

ip addr add 192.168.1.2/24 dev veth0

ip link set dev veth0 up

ip netns exec charles-netns ip addr add 192.168.1.1/24 dev veth1

ip netns exec charles-netns ip link set dev veth1 up

查找veth-pair

ip netns exec charles-netns ethtool -S veth1

2. 网桥实验——实现多个命令空间互联

创建两个命令空间: charles-netns-1, charles-netns-2

ip netns add charles-netns-1

ip netns add charles-netns-2

创建2个veth-pair

ip link add veth1-local type veth peer name veth1-peer

ip link add veth2-local type veth peer name veth2-peer

添加veth1-peer,veth2-peer到不同的命名空间

ip link set veth1-peer netns charles-netns-1

ip link set veth2-peer netns charles-netns-2

配置veth-pair IP地址

ip addr add 192.168.1.2/24 dev veth1-local

ip addr add 192.168.1.4/24 dev veth2-local

ip netns exec charles-netns-1 ip addr add 192.168.2.2/24 dev veth1-peer

ip netns exec charles-netns-2 ip addr add 192.168.2.4/24 dev veth2-peer

UP网卡

ip link set dev veth1-local up

ip link set dev veth2-local up

ip netns exec charles-netns-1 ip link set dev veth1-peer up

ip netns exec charles-netns-2 ip link set dev veth2-peer up

创建bridge

brctl addbr br0

brctl addif br0 veth1-local

brctl addif br0 veth2-local

ip addr add 192.168.1.1/24 dev br0

ip addr add 192.168.2.1/24 dev br0

ip link set dev br0 up

添加路由

ip netns exec charles-netns-1 ip route add default via 192.168.1.1 dev veth1-peer

ip netns exec charles-netns-2 ip route add default via 192.168.2.1 dev veth2-peer

3. 命名空间网卡访问外网实验

MASQUERADE

#打开IP转发

sysctl -w net.ipv4.conf.all.forwarding=1

#对Namespace中的包添加网络地址转换

#添加规则

iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE

#删除规则

iptables -t nat -D POSTROUTING -s 172.18.0.0/24 -o eth0 -j MASQUERADE

#列出规则

iptables-save

验证测试:

ip netns exec charles-netns-1 bash

ping www.baidu.com

PING www.a.shifen.com (220.181.112.244) 56(84) bytes of data.

64 bytes from 220.181.112.244 (220.181.112.244): icmp_seq=1 ttl=52 time=5.37 ms

64 bytes from 220.181.112.244 (220.181.112.244): icmp_seq=2 ttl=52 time=5.43 ms

64 bytes from 220.181.112.244 (220.181.112.244): icmp_seq=3 ttl=52 time=5.42 ms

抓包:

tcpdump -i eth0 -s0 -w eth0.pcap

DNAT

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.1.3:80

你可能感兴趣的:(Chapter 1 Deep leaning of docker)