Z.S.K.'s Records

CentOS 6.x上为Docker容器配置物理网段的静态IP

虚拟机安装centos6.5(ip范围从192.168.150.130-255,虚拟机网关192.168.150.2)

实验步骤:

0.停止docker:
service docker stop

1.安装brctl
yum install bridge-utils

2.配置桥接接口

brctl addbr br0

brctl addif br0 eth0

3.这是br0的配置文件ifcfg-br0:

vim /etc/sysconfig/network-script/ifcfg-br0(可复制ifcfg-eth0)

centos-docker-ip1

4.这是eth0的配置文件ifcfg-eth0:

vim /etc/sysconfig/network-script/ifcfg-eth0

centos-docker-ip2

5.重启网络:
service network restart
ip addr

centos-docker-ip3

ifcofnig

centos-docker-ip4

6.配置Docker使用br0

1
2
3
ip link set dev docker0 down`
brctl delbr docker0
iptables -t nat -F POSTROUTING

7.修改docker变量使用br0:

vim /etc/sysconfig/docker
other_args="-b=br0"

centos-docker-ip5

8.启动docker:service docker start
查看 iptables是否正常:
iptables -t nat -L -n

centos-docker-ip6

9.启动docker容器并设置ip:
启动docker容器:

1
docker run -ti --name docker1 --net=none --rm -v /usr/local/nginx/html:/usr/share/nginx/html:ro nginx:V4 /bin/bash

docker attach

查看ip addr 只有一个lo

centos-docker-ip7

10.在宿主机上执行如下脚本 格式如下:脚本 容器id 容器ip 子网掩码 网关 网络通道名

1
./docker-staticIP.sh e4cbb0f311a7 192.168.150.145 24 192.168.150.2 veth2

脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#/bin/bash
if [ -z $1 ] || [ -z $2 ] || [ -z $3 ] || [ -z $4 ] || [ -z $5 ];
then
echo "*****Input the necessary parameters: CONTAINERID IP MASK GATEWAY ETHNAME"
echo "*****Call the script like: sh manual_con_static_ip.sh b0e18b6a4432 192.168.5.123 24 192.168.5.1 deth0"
exit
fi
CONTAINERID=$1
SETIP=$2
SETMASK=$3
GATEWAY=$4
ETHNAME=$5
#判断宿主机网卡是否存在
ifconfig $ETHNAME > /dev/null 2>&1
if [ $? -eq 0 ]; then
read -p "$ETHNAME exist,do you want delelte it? y/n " del
if [[ $del == 'y' ]]; then
ip link del $ETHNAME
else
exit
fi
fi
pid=`docker inspect -f '{{.State.Pid}}' $CONTAINERID`
mkdir -p /var/run/netns
find -L /var/run/netns -type l -delete
if [ -f /var/run/netns/$pid ]; then
rm -f /var/run/netns/$pid
fi
ln -s /proc/$pid/ns/net /var/run/netns/$pid
ip link add $ETHNAME type veth peer name B
brctl addif br3 $ETHNAME
ip link set $ETHNAME up
ip link set B netns $pid
#先删除容器内已存在的eth0
ip netns exec $pid ip link del eth0 > /dev/null 2>&1
#设置容器新的网卡eth0
ip netns exec $pid ip link set dev B name eth0
ip netns exec $pid ip link set eth0 up
ip netns exec $pid ip addr add $SETIP/$SETMASK dev eth0
ip netns exec $pid ip route add default via $GATEWAY

11.在容器中ip addr就多一个eth0网络

centos-docker-ip8

12.在宿主机中查看ip addr 也多了一个veth2

centos-docker-ip9

13.游览器中访问容器的nginx,显示成功且容器中打印日志

centos-docker-ip10

14.测试时遇到如下问题:

centos-docker-ip11

解决办法:安装最新版的iproute:

1
2
wget https://repos.fedorapeople.org/openstack/EOL/openstack-grizzly/epel-6/iproute-2.6.32-130.el6ost.netns.2.x86_64.rpm
rpm -ivh --replacefiles ./iproute-2.6.32-130.el6ost.netns.2.x86_64.rpm

参考文章:

转载请注明原作者: 周淑科(https://izsk.me)


 wechat
Scan Me To Read on Phone
I know you won't do this,but what if you did?