Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm perfectly happy with the IP range that docker is giving me by default 176.17.x.x, so I don't need to create a new bridge, I just want to give my containers a static address within that range so I can point client browsers to it directly. I tried using

RUN echo "auto eth0" >> /etc/network/interfaces RUN echo "iface eth0 inet static" >> /etc/network/interfaces RUN echo "address 176.17.0.250" >> /etc/network/interfaces RUN echo "netmask 255.255.0.0" >> /etc/network/interfaces RUN ifdown eth0 RUN ifup eth0 

from a Dockerfile, and it properly populated the interfaces file, but the interface itself didn't change. In fact, running ifup eth0 within the container gets this error:

RTNETLINK answers: Operation not permitted Failed to bring up eth0

like image 916
dlanced Avatar asked Aug 27 '14 14:08

dlanced


People also ask

Can a Docker container have its own IP address?

The answer is: you can configure it. Create the container with --network host and it will use the host ip. There are other modes. Refer to the documentation above.


1 Answers

I have already answered this here https://stackoverflow.com/a/35359185/4094678 but 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/

like image 136
cantSleepNow Avatar answered Sep 21 '22 18:09

cantSleepNow