配置容器网络
使用–net=none 参数,可以自行的配置网络,让容器具有网络访问的权限!
- 启动一个/bin/bash容器,指定–net=none参数
[root@localhost ~]# docker run -i -t -d --net=none ubuntu /bin/bash
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
7b1a6ab2e44d: Pull complete
Digest: sha256:626ffe58f6e7566e00254b638eb7e0f3b11d4da9675088f4781a50ae288f3322
Status: Downloaded newer image for ubuntu:latest
9f2da5eac031422517e0919700748bcd8c13747014ef5d0b4ccad1d975514c81
- 查看当前运行容器ID,创建网络命名空间
[root@localhost ~]# docker inspect -f '{{.State.Pid}}' 9f
63995
[root@localhost ~]# mkdir -p /var/run/netns
[root@localhost ~]# ln -s /proc/63995/ns/net /var/run/netns/63995
- 检查桥接网卡的IP和子网掩码的信息
[root@localhost ~]# ip addr show docker0
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:a5:52:8e:bb brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:a5ff:fe52:8ebb/64 scope link
valid_lft forever preferred_lft forever
- 安装brctl
[root@localhost ~]# yum install bridge-utils -y
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirrors.aliyun.com
* updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package bridge-utils.x86_64 0:1.5-9.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
========================================================================================================================
Package Arch Version Repository Size
========================================================================================================================
Installing:
bridge-utils x86_64 1.5-9.el7 base 32 k
Transaction Summary
========================================================================================================================
Install 1 Package
Total download size: 32 k
Installed size: 56 k
Downloading packages:
bridge-utils-1.5-9.el7.x86_64.rpm | 32 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : bridge-utils-1.5-9.el7.x86_64 1/1
Verifying : bridge-utils-1.5-9.el7.x86_64 1/1
Installed:
bridge-utils.x86_64 0:1.5-9.el7
Complete!
- 创建一对veth pair 接口A和B,绑定A到网桥docker0,并启用它!
[root@localhost ~]# ip link add A type veth peer name B
[root@localhost ~]# brctl addif docker0 A
[root@localhost ~]# ip link set A up
- 将B放到容器的网络命名空间,为eth0,启动它并配置一个可用的IP和默认网关!
[root@localhost ~]# ip link set B netns 63995
[root@localhost ~]# ip netns exec 63995 ip link set dev B name eth0
[root@localhost ~]# pid=63995
[root@localhost ~]# ip netns exec $pid ip link set eth0 up
[root@localhost ~]# ip netns exec $pid ip addr add 172.17.0.99/16 dev eth0
[root@localhost ~]# ip netns exec $pid ip route add default via 172.17.0.1