11 Docker為容器分配指定物理IP位址

2022-03-07 14:28:00 字數 2507 閱讀 4194

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

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會丟失,此時需要重新執行該指令碼一次

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"

exitfi

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

fifi

#獲取容器的程序pid號

pid=`docker inspect -f '}' $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/$pidfi

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

bash-4.3# sh docker_create.sh

bash-4.3# sh docker_ipaddr.sh docker_name ip netmask(24) gateway deth0

容器分配固定物理ip位址

Docker容器固定IP分配

我們在使用docker run 建立docker 容器時,可以用 net 選項指定容器的網路模式,docker 有以下4 種網路模式 host模式,使用 net host 指定。container模式,使用 net container name or id 指定。none模式,使用 net none...

Docker容器固定IP分配

我們在使用docker run 建立docker 容器時,可以用 net 選項指定容器的網路模式,docker 有以下4 種網路模式 host模式,使用 net host 指定。container模式,使用 net container name or id 指定。none模式,使用 net none...

Docker容器固定IP分配

我們在使用docker run 建立docker 容器時,可以用 net 選項指定容器的網路模式,docker 有以下4 種網路模式 host模式,使用 net host 指定。container模式,使用 net container name or id 指定。none模式,使用 net none...