ps: 该脚本从网上找的
1. 创建容器
bash-4.3# cat docker_create.sh
#!/bin/bash
images="sshd:centos6.8"
name="docker_211"
dir="/data/docker/volumes/docker_211"
#ip="192.168.1.56/24"
docker run -itd --net=none -h $name -v $dir:/data --privileged --name $name $images /bin/bash
2. 为容器配置静态IP地址
bash-4.3# cat 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
#判断宿主机网卡是否存在
fconfig $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 br0 $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
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
2c21a8a52e4c239650be60dc5e3db47f0eb4a39222f42df36d40b7aa0f036525
bash-4.3# sh docker_ipaddr.sh docker_211 172.168.200.211 24 172.168.200.254 deth211
bash-4.3# ssh root@172.168.200.211
root@172.168.200.211's password:
Last login: Wed Aug 10 04:17:37 2016 from aca8c856.ipt.aol.com
[root@docker_211 ~]#