How can I set a static IP address in a Docker container? How can I set a static IP address in a Docker container? docker docker

How can I set a static IP address in a Docker container?


I have already answered this here https://stackoverflow.com/a/35359185/4094678but I see now that this question is actually older then the aforementioned one, so I'll copy the answer as well:

Easy with Docker version 1.10.1, build 9e83765.

First you need to create you own docker network (mynet123)

docker network create --subnet=172.18.0.0/16 mynet123

than simply run the image (I'll take ubuntu as example)

docker run --net mynet123 --ip 172.18.0.22 -it ubuntu bash

then in ubuntu shell

ip addr

Additionally you could use
--hostname to specify a hostname
--add-host to add more entries to /etc/hosts

Docs (and why you need to create a network) at https://docs.docker.com/engine/reference/commandline/network_create/


I'm using the method written here from the official Docker documentation and I have confirmed it works:

# At one shell, start a container and# leave its shell idle and running$ sudo docker run -i -t --rm --net=none base /bin/bashroot@63f36fc01b5f:/## At another shell, learn the container process ID# and create its namespace entry in /var/run/netns/# for the "ip netns" command we will be using below$ sudo docker inspect -f '{{.State.Pid}}' 63f36fc01b5f2778$ pid=2778$ sudo mkdir -p /var/run/netns$ sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid# Check the bridge's IP address and netmask$ ip addr show docker021: docker0: ...inet 172.17.42.1/16 scope global docker0...# Create a pair of "peer" interfaces A and B,# bind the A end to the bridge, and bring it up$ sudo ip link add A type veth peer name B$ sudo brctl addif docker0 A$ sudo ip link set A up# Place B inside the container's network namespace,# rename to eth0, and activate it with a free IP$ sudo ip link set B netns $pid$ sudo ip netns exec $pid ip link set dev B name eth0$ sudo ip netns exec $pid ip link set eth0 up$ sudo ip netns exec $pid ip addr add 172.17.42.99/16 dev eth0$ sudo ip netns exec $pid ip route add default via 172.17.42.1

Using this approach I run my containers always with net=none and set IP addresses with an external script.


Actually, despite my initial failure, @MarkO'Connor's answer was correct. I created a new interface (docker0) in my host /etc/network/interfaces file, ran sudo ifup docker0 on the host, and then ran

docker run --net=host -i -t ... 

which picked up the static IP and assigned it to docker0 in the container.

Thanks!