Recently i had to setup multiple docker containers running on the same host but using different IP addresses for both outgoing and incoming. For the incoming it’s easy you just need to specify the IP address on the ports that you’re opening, like:
docker run something ip:80
The problem seems to be for the outgoing traffic leaving the container. After looking at several StackOverflow’s answers and setups, that were too complex i concluded that docker doesn’t seem to have an integrated solution for this, so in order to accomplish this, i had to work with itpables.
First created a network to isolate the container traffic:
docker network create outgoing-traffic
connected the container to the network:
docker network connect outgoing-traffic container-name
disconnected any existing network:
docker network disconnect default container-name
Set the iptables (On debian i had to install iptables-persistent so that rules persist through reboots):
iptables -t nat -I POSTROUTING -s <docker-network-CIDR> -j SNAT --to-source host-outgoin-ip
In essence what it does, from my understanding is. After all the routing is done iptables modifies the headers of the packets to replace the source IP.
That’s it, the container should be sending traffic through the specified IP while the others will be using the default IP on the interface.