I have 4 NICs installed in my host PC. I want to launch different docker's containers with binding different physical NICs to each container. How can I do for docker? For VirtualBox, this can be done with creating bridge adapter for each VM of the physical NICs.
When you expose ports on Docker using the -P
or -p
options it is just creating an iptables Destination NAT or DNAT entry. You can even look at those entries by running the command below.
iptables -t nat -nL
...
Chain DOCKER (2 references)
target prot opt source destination
DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:8001 to:172.17.0.19:80
DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:8002 to:172.17.0.20:80
By default docker will use the 0.0.0.0/0 (i.e. all interfaces) specification to forward ports too and from docker container hosts. However you could replace those rules to forward only from selected interfaces.
So Say I have two web-servers both wanting to listen on port 80. I would run them as follows. Note that I am not exposing any ports. This so that only our created IP Tables rule allows access to these nodes.
docker run --name web1 -t something/web-server
docker run --name web2 -t something/web-server
Run docker inspect to get the Virtual IP of the container
docker inspect web1 | grep IPAddress
IPAddress": "172.17.0.19",
docker inspect web2 | grep IPAddress
IPAddress": "172.17.0.20",
Now add in DNAT rules for the specific interfaces:
iptables -t nat -A DOCKER -p tcp -d [INTERFACE_1_IP] --dport 80 -j DNAT --to-destination 172.17.0.19:80
iptables -t nat -A DOCKER -p tcp -d [INTERFACE_2_IP] --dport 80 -j DNAT --to-destination 172.17.0.20:80
Update 2018-05
After doing some research (which is not very easy if you don't know the right keywords) on this topic I believe there are updated ways to do this depending on whether you are trying to bind Linux or Windows containers to physical NIC ports (solutions not tested):
Linux: Use a macvlan
network configuration. See this docker doc
Windows: Use an External Virtual Switch
for each docker container. See this Microsoft doc
EDIT: There is an even easier way to do this on Windows that automatically sets up the External Virtual Switch as noted in this Microsoft doc. I have tested this method and it works great. This uses a transparent
docker network type.
Hopefully this helps future googlers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With