创建docker容器
docker run -it --name=yh -h yh --net=none debian:sshd bash ### 确保使用--net=none参数,此时新建的容器内不会创建网卡
docker ps
此时登录容器查看IP,会发现没有eth0网卡:
root@yh:/# ifconfig -a |
CentOS6.6升级iproute
为了支持ip netns命令,需要对CentOS6.6进行升级:
rpm -ivh http://www.elrepo.org/elrepo-release-6-6.el6.elrepo.noarch.rpm
yum --enablerepo=elrepo-kernel install kernel-lt -y
vi /etc/grub.conf ## 修改default=0,默认启动新内核
reboot
uname -r
yum install -y http://rdo.fedorapeople.org/rdo-release.rpm ### 更新rdo仓库
vim /etc/yum.repos.d/rdo-release.repo ### 修改文件内容为如下
[openstack-juno] name=OpenStack Juno Repository baseurl=http://repos.fedorapeople.org/repos/openstack/openstack-icehouse/epel-6/ enabled=1 skip_if_unavailable=0 gpgcheck=0 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-RDO-Juno |
yum --enablerepo=openstack-juno install iproute ### 更新iproute
rpm -q iproute
设置静态IP
modify_docker_ip.sh:
#/bin/bash if [ -z $1 ] || [ -z $2 ] || [ -z $3 ] || [ -z $4 ] || [ -z $5 ]; then echo "Usage: $0 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` echo pid=$pid 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 docker0 $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 |
执行如下命令为容器创建网卡,并分配静态IP:
./modify_docker_ip.sh 8feff00a0a26 172.17.0.2 16 172.17.42.1 deth0
其中:8feff00a0a26 是容器ID,172.17.0.2是容器的静态IP,16是掩码,172.17.42.1是容器的网关地址(即运行容器的系统中docker0的IP),deth0为新建的宿主机网卡名(对应容器内的eth0)
此时查看宿主机IP:
[root@node0003 ~]# ifconfig docker0 Link encap:Ethernet HWaddr 56:84:7A:FE:97:99 |
在容器内查看IP:
root@yh:/# ifconfig -a lo Link encap:Local Loopback |
原文地址:http://yuanhuan.blog.51cto.com/3367116/1652690