skip to Main Content

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


  1. 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 run

    docker run -p 172.18.0.3:80:8080 ...
    

    and 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 the docker run --ip option. If you ran ifconfig 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.

    Login or Signup to reply.
  2. 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:

    docker network create -d ipvlan --subnet=172.18.0.1/16 
    -o ipvlan_mode=l2 my_network
    

    Then run your docker container within that network and assign an IP address:

    docker run --name myApp --net my_network --ip 172.18.0.3 -dt ubuntu
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search