DOCKER手動配置容器的網路
預設情況下,啟動容器不加--net引數啟動容器是可以通過docker0獲取ip地址並連線網路的
手動配置更加靈活,並能瞭解原理和細節
1、啟動容器,指定--net=none
[[email protected] run]# docker run -it --net=none -d tomcat:v3
24ca74a9f2a81478f1989035374cc059effe18b0644a3530de56d8b4abd65a12
此時容器無法連線網路
[[email protected] ~]# docker exec -it 24ca74a9f2a8 bash
[email protected]:/usr/local/tomcat# ping www.sina.com.cn
ping: www.sina.com.cn: Temporary failure in name resolution
[email protected]:/usr/local/tomcat#
[email protected]:/usr/local/tomcat# ping www.baidu.com
ping: www.baidu.com: Temporary failure in name resolution
2、查詢容器的程序ID
[[email protected] run]# docker inspect -f '{{.State.Pid}}' 24ca74a9f2a8
6663
3、為容器的程序創造名稱空間
[[email protected] run]# mkdir -p /var/run/netns
[[email protected] run]# ln -s /proc/6663/ns/net /var/run/netns/6663
4、查詢docker0的IP
[[email protected] ~]# ip addr | grep docker0
docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
inet 172.17.0.1/16 scope global docker0
5、建立veth peer的介面A和B,將介面A橋接到docker0,將介面B放到容器的第三步定義的名稱空間,並命名為eth0,指定IP地址,並指定網路預設的下一跳地址為物理機的docker0的IP
[[email protected] run]# ip link add A type veth peer name B #建立veth peer的介面A和B
[[email protected] run]# brctl addif docker0 A #將介面A橋接到docker0
[[email protected] run]# ip link set A up #UP該埠
[[email protected] run]# ip link set B netns 6663 #將介面B放到容器的第三步定義的名稱空間
[[email protected] run]# ip netns exec 6663 ip link set dev B name eth0 #命名為eth0
[[email protected] run]# ip netns exec 6663 ip link set eth0 up #UP該埠
[[email protected] run]# ip netns exec 6663 ip addr add 172.17.0.99/16 dev eth0 #指定容器的IP地址
[[email protected] run]# ip netns exec 6663 ip route add default via 172.17.0.1 #指定網路預設下一跳地址為物理機docker0的IP
6、測試網路,eth0為上一步指定的IP,下一跳物理機docker0也將資料包轉發出去,可以ping通外網
[email protected]:/usr/local/tomcat# ip addr | grep eth0
eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
inet 172.17.0.99/16 scope global eth0
[email protected]:/usr/local/tomcat# ping www.baidu.com
PING www.a.shifen.com (14.215.177.38) 56(84) bytes of data.
64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=1 ttl=127 time=16.8 ms
64 bytes from 14.215.177.38 (14.215.177.38): icmp_seq=2 ttl=127 time=12.8 ms