给容器分配局域网IP

准备工作:

1 方便获取容器的ip 和pid的几个脚本:docker-pi    docker-pid


docker-ip

#!/bin/sh

 

exec docker inspect --format '{{.NetworkSettings.IPAddress }}' "$@"

docker-pid

#!/bin/sh

exec docker inspect --format '{{ .State.Pid }}'"$@"

将文件增加执行权限chmod +x  docker-pid  chomod +x docker-ip

放入/usr/local/bin

 

2 下载安装nsenter   在容器外修改容器配置

wget https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz

解压&& 进入目录

# ./autogen.sh

# ./configure --without-ncurses && make

# cp nsenter /user/local/bin

 

 

3 执行如下脚本config-network.sh

 222.211.65.74是docker 容器所在主机em1网卡ip,222.211.65.79是需要给容器分配的公网地址

#! /bin/bash

 

set -x

 

IP="222.211.65.79"

MASK="255.255.255.192"

GATEWAY="222.211.65.65"

DNS="61.139.2.69"

 

brctl addbr br-eth

ip link set br-eth up

 

brctl addif br-eth  em1

ip addr add 222.211.65.74/26  dev br-eth

brctl show br-eth

ip addr show br-eth

 

ip addr del 222.211.65.74 dev em1

#ip addr add 192.168.0.142 dev br-eth

ifconfig br-eth 222.211.65.74  netmask $MASK

 

# change route infos

ip route del default

ip route add default via $GATEWAY  dev br-eth

ip route

 

docker run -itd --namehost  hub.ghostcloud.cn/ubuntu:14.04

ip link add host-inttype veth peer name host-ext

 

brctl  addifbr-eth  host-ext

ip link set host-ext up

ip link set netns $(docker-pid host) dev host-int

 

#start host-int

nsenter -t $(docker-pid host) -n ip link set host-int up

#config container ip

nsenter -t $(docker-pid host) -n ip addr add  $IP/26 dev host-int

 

#add route to  container

nsenter -t $(docker-pid host) -n ip route del default

nsenter -t $(docker-pid host) -n ip route add default via$GATEWAY  dev host-int

nsenter -t $(docker-pid host) -n echo "nameserver$DNS" >> /etc/resolv.conf

4 验证

主机gc03-000000-0009ping容器(222.211.65.79):

 

2 容器ping局域网主机:


 

公司局域网ping容器:

 


5 Trouble shoot

检查主机路由:


检查br-eth网桥


检查容器内部路由


检查host-ext和host-int


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐