Assign static IP to Docker container

2019-01-01 08:11发布

I'm now trying to assign a static IP 172.17.0.1 when a Docker container be started up.

I use port 2122 as the ssh port of this container so that I let this container listen port 2122.

sudo docker run -i -t -p 2122:2122 ubuntu

This command will run a Docker container with a random IP like 172.17.0.5, but I need to assign a specific IP to the container.

The following shell script is what I reference Docker documentation in advanced network settings.

pid=$(sudo docker inspect -f '{{.State.Pid}}' <container_name> 2>/dev/null)
sudo rm -rf /var/run/netns/*
sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid
sudo ip link add A type veth peer name B
sudo brctl addif docker0 A
sudo ip link set A up
sudo ip link set B netns $pid
sudo ip netns exec $pid ip link set eth0 down
sudo ip netns exec $pid ip link delete eth0
sudo ip netns exec $pid ip link set dev B name eth0
sudo ip netns exec $pid ip link set eth0 address 12:34:56:78:9a:bc
sudo ip netns exec $pid ip link set eth0 down
sudo ip netns exec $pid ip link set eth0 up
sudo ip netns exec $pid ip addr add 172.17.0.1/16 dev eth0
sudo ip netns exec $pid ip route add default via 172.17.42.1

This shell script will assign a static IP 172.17.0.1 and link to the world fine. But whenever I try to ssh to this container from my local, it didn't work. What's the problem possibly I met?

标签: docker
8条回答
其实,你不懂
2楼-- · 2019-01-01 08:37

I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.

This article describes technique how to assign static IP to the container on Debian:

  1. Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false". I assume that br0 bridge is already configured.

  2. Container should be started with --cap-add=NET_ADMIN --net=bridge

  3. Inside container pre-up ip addr flush dev eth0 in /etc/network/interfaces can be used to dismiss IP address assigned by Docker as in following example:


auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
    pre-up ip addr flush dev eth0
    address 192.168.0.249
    netmask 255.255.255.0
    gateway 192.168.0.1
  1. Container's entry script should begin with /etc/init.d/networking start. Also entry script needs to edit or populate /etc/hosts file in order to remove references to Docker-assigned IP.
查看更多
弹指情弦暗扣
3楼-- · 2019-01-01 08:39

This works for me.

Create a network with docker network create --subnet=172.17.0.0/16 selnet

Run docker image docker run --net selnet --ip 172.18.0.2 hub

At first I got

docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets. ERRO[0000] error waiting for container: context canceled

Solution: Increased the 2nd quadruple of the ip [.18. instead of .17.]

查看更多
登录 后发表回答