I need to run a docker container (hosting nginx), such that the container gets a static IP address on the host network. Example:
Suppose the host has IP 172.18.0.2/16 then I would like to give 172.18.0.3/16 to the docker container running on the host. I’d like the other physical machines in the host’s network to be able to connect to the container at 172.18.0.3/16.
I have tried the solution described by: https://qiita.com/kojiwell/items/f16757c1f0cc86ff225b, (without vegrant) but it didn’t help. I’m not sure about the --subnet
option that needed to be supplied to the docker network create
command.
As suggested in this post, I was trying to do:
docker network create
--driver bridge
--subnet=<WHAT TO SUPPLY HERE?>
--gateway=<WHAT TO SUPPLY HERE?>
--opt "com.docker.network.bridge.name"="docker1"
shared_nw
# Add my host NIC to the bridge
brctl addif docker1 eth1
Then start the container as:
docker run --name myApp --net shared_nw --ip 172.18.0.3 -dt ubuntu
Somehow it did not work. I will appreciate if someone could point me to the right direction about how to set such a thing up. Grateful!
2
Answers
The
docker run -p
option optionally accepts a bind-address part, which specifies a specific host IP address that will accept inbound connections. If your host is already configured with the alternate IP address, you can just runand
http://172.18.0.3/
(on the default HTTP port 80) will forward to port 8080 in the container.Docker has a separate internal IP address space for containers, that you can almost totally ignore. You almost never need the
docker network create --subnet
option and you really never need thedocker run --ip
option. If you ranifconfig
inside this container you’d see a totally different IP address, and that would be fine; the container doesn’t know what host ports or IP addresses (if any) it’s associated with.On your use-case the
ipvlan
docker network could work for you.using your assumptions about the host ip address and mask, you could create the network like this:
Then run your docker container within that network and assign an IP address:
Note that any exposed port of that container will be available on the
172.18.0.3
ip address, but any other services on your host will not be reachable with that IP address.You can find more info on ipvlan at the official docker documentation