8

How do I fix a static IP for a container ?

First I start a container and inspect it, it says

"NetworkSettings": {
    "IPAddress": "XX.XX.206.98",
    "IPPrefixLen": 27,
    "Gateway": "XX.XX.206.105",
    "Bridge": "public",
    "PortMapping": null,
    "Ports": {}
},

then I stop it, and restart, it like

"NetworkSettings": {
    "IPAddress": "XX.XX.206.99",
    "IPPrefixLen": 27,
    "Gateway": "XX.XX.206.105",
    "Bridge": "public",
    "PortMapping": null,
    "Ports": {}
},

As you can see, it changed. I just created a bridge named public, and start docker with -b=public added. How can I set a static IP for a container?

Phlume
  • 3,075
  • 2
  • 19
  • 38
user3204937
  • 91
  • 1
  • 3
  • this is a important feature, suppose you have a db service run as docker and all jdbc url is fixed to that ip addr. you have to modify every jdbc url after that db container restarted. – hihell Jul 19 '16 at 09:33

1 Answers1

4

FROM DOCKER 1.10 ON

# create a new bridge network with your subnet and gateway for your ip block
$ docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 iptastic

# run a nginx container with a specific ip in that block
$ docker run --rm -it --net iptastic --ip 203.0.113.2 nginx

# curl the ip from any other place (assuming this is a public ip block duh)
$ curl 203.0.113.2

UPDATE

Now the only way to obtain a static IP is through two scripts: pipework or ovs-docker

There is a strong direction towards using Open vSwitch as the "battery included" version of multi hosted docker containers.

Keep an eye on socketplane.


This behavior is by design.

There is a very interesting discussion for changing it in future releases.

Up to now the only way you can do it is falling back to linux containers:

docker run \
-n=false \
-lxc-conf="lxc.network.type = veth" \
-lxc-conf="lxc.network.ipv4 = 172.16.42.20/24" \
-lxc-conf="lxc.network.ipv4.gateway = 172.16.42.1" \
-lxc-conf="lxc.network.link = docker0" \
-lxc-conf="lxc.network.name = eth0" \
-lxc-conf="lxc.network.flags = up" \
-i -t my_image:my_tag /bin/bash

So the -n=false disables the automatic docker networking and all the -lxc-conf options are to actually define the virtual network according to your needs.

tommasop
  • 18,495
  • 2
  • 40
  • 51
  • this does not work anymore, can you update your answer? – Louis Kottmann Jul 19 '14 at 16:29
  • Actually I see two ways of addressing the issue: https://github.com/jpetazzo/pipework and https://docs.docker.com/articles/networking/#building-a-point-to-point-connection none of these is a real answer to the issue. – tommasop Jul 19 '14 at 21:17
  • It is a hack indeed! But a hack made by one of docker's creators so it is an original hack (in the same sense as the original sin). And most importantly it is easy to read and understand what's happening behind and this is a huge plus. I'm using it too! – tommasop Jul 20 '14 at 05:52