Iptables – Route outgoing connections from a docker container through a specific IP

dockeriptables

I have a docker host machine with a single physical network interface (eth0) and multiple IP addresses assigned to it using IP aliasing (eth0:1, eth0:2, eth0:3).

I would like to run several docker containers so that each of them is using it's own IP address for outgoing calls to the internet. Preferably they would be also reachable on the same IP when connecting from container to container.

How do I setup docker and iptables for this to work? And with what parameters I need to run each of the containers afterwards?

Best Answer

eth0 -> 192.168.0.1

eth0:1 -> 192.168.0.2

eth0:2 -> 192.168.0.3

eth0:3 -> 192.168.0.4

docker run --name=web01 -p 192.168.0.1:80:80 ....

docker run --name=web02 -p 192.168.0.2:80:80 ....

docker run --name=web03 -p 192.168.0.3:80:80 ....

docker run --name=web04 -p 192.168.0.4:80:80 ....

They will be created DNAT rules:

Chain DOCKER (2 references) pkts bytes target prot opt in out source destination
0 0 DNAT tcp -- !docker0 * 0.0.0.0/0 192.168.0.1 tcp dpt:80 to:172.17.0.1:80

pkts bytes target prot opt in out source destination
0 0 DNAT tcp -- !docker0 * 0.0.0.0/0 192.168.0.2 tcp dpt:80 to:172.17.0.2:80

...

traffic generated container falls under the rule:

Chain POSTROUTING (policy ACCEPT 430M packets, 26G bytes) pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0

p.s.

In linux we can use many ip without alias

ip a a 192.168.0.1/24 dev eth0

ip a a 192.168.0.2/24 dev eth0 ....

Related Topic