手动为容器设置ip地址
1、安装bridge-utils
# aptitude install -y bridge-utils
2、配置网桥
# vim /etc/network/interfaces
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
auto eth1
iface eth1 inet manual
auto veth0
iface veth0 inet static
address 122.14.206.140
netmask 255.255.254.0
gateway 122.14.206.1
bridge_ports eth0
bridge_fd 9
bridge_hello 2
bridge_maxage 12
bridge_stp on
auto veth1
iface veth1 inet static
address 192.168.5.86
netmask 255.255.240.0
gateway 122.14.206.1
bridge_ports eth1
bridge_fd 9
bridge_hello 2
bridge_maxage 12
bridge_stp on
# /etc/init.d/networking restart
3、修改容器IP地址的脚本
# cat mkipinner.sh
#/bin/bash
#判断是否给定位置参数,如果没有则提示用法
if [ -z $1 ] || [ -z $2 ] || [ -z $3 ] || [ -z $4 ];
then
echo "*****Input the necessary parameters: CONTAINERID IP MASK GATEWAY ETHNAME"
echo "*****Use the script like: sh manual_con_static_ip.sh a122-v00 192.168.5.123 24 192.168.5.1"
exit
fi
#为4个位置参数设置变量
CONTAINERID=$1
SETIP=$2
SETMASK=$3
GATEWAY=$4
#判断容器是否已存在
ethlist=($(docker ps|grep -w "$CONTAINERID"|awk '{print $1}'))
if [[ ${#ethlist[@]} -ne 1 ]];then
echo "can not ensure the container"
exit 1
fi
#设置变量name等于容器ID,设定虚拟网卡名称等于veth+$name前6位
echo $*
name=${ethlist[0]}
ETHNAME="veth${name:0:6}"
#判断该虚拟网卡网卡是否存在,如果存在,则提示是否删除
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
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
#创建名称空间,将容器的网络名称空间软链接到/var/run/netns/
ln -s /proc/$pid/ns/net /var/run/netns/$pid
#添加一对虚拟网卡
ip link add $ETHNAME type veth peer name $pid"1"
#将虚拟网卡添加到网桥veth1
brctl addif veth1 $ETHNAME
#启动虚拟网卡
ip link set $ETHNAME up
#将虚拟网卡添加到容器的网络名称空间
ip link set $pid"1" netns $pid
#删除容器内已存在的eth1
ip netns exec $pid ip link del eth1 > /dev/null 2>&1
#将容器内的网卡$pid"1"重命名为eth1,并启动
ip netns exec $pid ip link set dev $pid"1" name eth1
ip netns exec $pid ip link set eth1 up
#为容器的eth1网卡设置IP地址和掩码,添加默认网关
ip netns exec $pid ip addr add $SETIP/$SETMASK dev eth1
ip netns exec $pid ip route add default via $GATEWAY
4、脚本使用方法
/root/bin/mkipinner.sh <container_name> <ip_address> <netmask_num> <gateway>
示例:
# /root/bin/mkipinner.sh uy01-05-v10 192.168.10.186 20 192.168.1.254
5、单独修改网关
# ip netns exec `docker inspect -f '{{.State.Pid}}' $CONTAINERID` ip route del default via 192.168.1.248
# ip netns exec `docker inspect -f '{{.State.Pid}}' $CONTAINERID` ip route add default via 192.168.1.254
合成一条命令,尽量减少网络中断时间
# for id in `cat id`;do ip netns exec `docker inspect -f '{{.State.Pid}}' $id` ip route del default via 192.168.1.248 && ip netns exec `docker inspect -f '{{.State.Pid}}' $id` ip route add default via 192.168.1.254;done
在容器内测试网络
# route -n
# curl myip.oupeng.com
122.14.206.132