1.环境:Centos7
2.运行一个容器
[root@idc ~]# docker run -it --rm --name=mynetwork --net=none centos:latest /bin/bash
#--net=none:docker不对容器进行网络配置,无网络配置
#--rm:容器停止后会清空容器,对容器的设置都将被清除
#容器运行后,再克隆一个会话进行下面的步骤
3.创建容器的网络命名空间
[root@idc ~]# PID=$(docker inspect -f '{{.State.Pid}}' mynetwork)
[root@idc ~]# mkdir -p /var/run/netns
[root@idc ~]# ln -s /proc/$PID/ns/net /var/run/netns/$PID
4.创建一对veth pair接口A和B,绑定A接口到网桥br0并启动它
[root@idc ~]# ip link add A type veth peer name B
[root@idc ~]# brctl addif br0 A
[root@idc ~]# ip link set A up
#如果brctl命令报错,则进行yum安装
#yum install bridge-utils
5.将接口B放到容器的网络命名空间,命名为eth0,并配置ip地址和网关,再启动
[root@idc ~]# ip link set B netns $PID
[root@idc ~]# ip netns exec $PID ip link set dev B name eth0
[root@idc ~]# ip netns exec $PID ip link set eth0 up
[root@idc ~]# ip netns exec $PID ip addr add 172.17.42.100/24 dev eth0
[root@idc ~]# ip netns exec $PID ip route add default via 172.17.42.1
6.到容器中查看ip
[root@3508b096cd89 /]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
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
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
128: eth0@if129: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default
qlen 1000
link/ether 76:29:d9:1f:fd:c1 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 172.17.42.100/24 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::7429:d9ff:fe1f:fdc1/64 scope link
valid_lft forever preferred_lft forever