11. Docker为容器分配指定物理IP地址
1. 给宿主机配置Br0网卡
bash-3.2# cd /etc/sysconfig/network-scripts/
bash-3.2# cp ifcfg-eth0 ifcfg-br0
bash-3.2# vim ifcfg-eth0
DEVICE=eth0
HWADDR=BC:5F:F4:5E:4A:AD
TYPE=Ethernet
UUID=b64d5263-4f16-453b-9971-ab052f101c9e
ONBOOT=yes
NM_CONTROLLED=yes
BRIDGE=br0
bash-3.2# vim ifcfg-br0
DEVICE=br0
TYPE=Bridge
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.1.40
NETMASK=255.255.255.0
GATEWAY=192.168.1.254
DNS1=192.168.1.254
DNS2=114.114.114.114
MTU=1500
bash-3.2# /etc/init.d/network restart
2. Docker创建容器脚本
bash-4.3# vim docker_create.sh
#!/bin/bash
images="centos6.8_x64:ssh"
name="docker_54"
dir="/data/docker/volumes/docker_54"
docker run -itd --net=none -h $name -v $dir:/data --privileged --name $name $images /bin/bash
有个问题就是容器重启后, 设定的ip会丢失,此时需要重新执行该脚本一次
3. 为容器配置ip地址
bash-4.3# vim docker_ipaddr.sh
#/bin/bash
if [ -z $1 ] || [ -z $2 ] || [ -z $3 ] || [ -z $4 ];
then
echo "*****Input the necessary parameters: CONTAINERID IP MASK GATEWAY"
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号
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 br0 $ETHNAME
ip link set $ETHNAME up
ip link set B netns $pid
ip netns exec $pid ip link del eth0 > /dev/null 2>&1
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
3. 使用方法
bash-4.3# sh docker_create.sh
bash-4.3# sh docker_ipaddr.sh docker_name IP NetMask(24) GateWay deth0
容器分配固定物理ip地址