创建一个没有网络配置的容器
[[email protected] ~]# docker run -i -t --rm --net=none alpine sh
/ #
打开另一个终端
查看容器id
[[email protected] ~]# docker ps -a
查找进程id
[[email protected] ~]# docker inspect -f ‘{{.State.Pid}}‘ 2aefc41dbdeb
9076
[[email protected] ~]# pid=9076
创建命名空间
[[email protected] ~]# mkdir -p /var/run/netns
[[email protected] ~]# ln -s /proc/$pid/ns/net /var/run/netns/$pid
查看桥接网卡的IP 和子网掩码信息
[[email protected] ~]# ip addr show docker0
5: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
link/ether 02:42:8e:e7:64:4a brd ff:ff:ff:ff:ff:ff
inet 172.18.0.1/16 brd 172.18.255.255 scope global docker0
valid_lft forever preferred_lft forever
创建一对"veth pair"接口A和B
[[email protected] ~]# sudo ip link add A type veth peer name B
绑定A接口到网桥docker0
[[email protected] ~]# sudo brctl addif docker0 A
并启用它
[[email protected] ~]# sudo ip link set A up
将B 接口放到容器的网络命名空间
[[email protected] ~]# sudo ip link set B netns $pid
命名为eth0
[[email protected] ~]# sudo ip netns exec $pid ip link set dev B name eth0
开启网络接口B
[[email protected] ~]# sudo ip netns exec $pid ip link set eth0 up
配置一个可用IP(桥接网段)
[[email protected] ~]# sudo ip netns exec $pid ip addr add 172.18.0.99/16 dev eth0
配置默认网关
[[email protected] ~]# sudo ip netns exec $pid ip route add default via 172.18.0.1
最后回到容器检查一下网卡配置
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
18: [email protected]: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP qlen 1000
link/ether 6e:b9:75:8e:f4:99 brd ff:ff:ff:ff:ff:ff
inet 172.18.0.99/16 scope global eth0
valid_lft forever preferred_lft forever
/ # ping baidu.com
PING baidu.com (123.125.114.144): 56 data bytes
64 bytes from 123.125.114.144: seq=0 ttl=53 time=2.827 ms
64 bytes from 123.125.114.144: seq=1 ttl=53 time=2.900 ms
^C
--- baidu.com ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 2.827/2.863/2.900 ms
原文地址:https://blog.51cto.com/13670314/2376970
时间: 2024-10-02 03:19:06