Assign IP address to docker container09 May 2016
Many times when working with docker containers I feel the need of assigning a known beforehand IP address to a container. This is a huge advantage if you want to control the network access to and from a container with a tool like iptables. However, current docker version (1.11.1) does not allow this operation out of the box, but there is an official way of achieving this. Thanks to
docker network command a user may create a fully customizable network and connect a container to it. You may find full information at the official Docker site, here.
I will start with a clean docker installation on a test vagrant machine (Ubuntu Trusty). After installing docker, as usual, you may see
docker0 network interface. This a default bridging interface. I will follow the documentation and create an isolated network using the same subnet, addresses and names.
So the first step is to create a new network:
This network will allow me to use a
172.25.255.254 address range. If I run
ifconfig now I will see that a new interface is created. In my case, docker calls it
br-98446a2a4f1f. Just to be sure I reboot my machine to see if this network persists across reboots and it does.
Now I want to start
nginx container with
172.25.0.2 address, I can do it with the following command:
If I get inside the container and run
ip addr command I will see that the assigned IP address is, in fact, the requested one:
Now, I will start another container just to check the connectivity between them:
So, if I get inside a second container I'm able to perform ping and telnet with the first one:
Time to check that linking between containers also works, I will start my containers this way:
Then, if I connect to
my_nginx_02 container I will be able to ping and telnet
As you can see
my_nginx_01 resolves to the IP address assigned during the startup. With this configuration, you may be able to control your security perimeter using
FORWARD chain in your