Docker Community Forums

Share and learn in the Docker community.

Use default route of host for outgoing traffic in Docker network

I have a cloud box running Ubuntu 18.04.5 LTS with the following IPs:

  • Primary IP: 203.0.113.199
  • Floating IP: 203.0.113.55

My goal is that all outgoing traffic from the box uses the floating IP as the source address.
For that I configured a virtual interface and assigned it the floating IP address:

auto eth0:1
iface eth0:1 inet static
    address 203.0.113.55
    netmask 32

This leads to the following output of ifconfig:

~$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 203.0.113.199  netmask 255.255.255.255  broadcast 203.0.113.199
        inet6 xxxx::xxxx:xxxx:xxxx:xxxx  prefixlen 64  scopeid 0x20<link>
        inet6 xxxx:xxxx:xxxx:xxxx::xxxx  prefixlen 64  scopeid 0x0<global>
        ether xx:xx:xx:xx:xx:xx  txqueuelen 1000  (Ethernet)
        RX packets 5316856  bytes 2082365743 (2.0 GB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2462967  bytes 404933411 (404.9 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth0:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 203.0.113.55  netmask 255.255.255.255  broadcast 0.0.0.0
        ether xx:xx:xx:xx:xx:xx  txqueuelen 1000  (Ethernet)

Then I (temporarily) set the default route to use the floating IP as the source address (172.31.1.1 is used as a default gateway of all servers public network interfaces at my cloud provider):

~$ ip route change default via 172.31.1.1 src 203.0.113.55

This leads to the desired effect when testing with curl from the terminal:

~$ curl -s -4 http://ifconfig.co
203.0.113.55

The desired source IP address is also used when using making a request inside a Docker container running with network mode host:

~$ docker run --rm --network=host curlimages/curl -s -4 http://ifconfig.co
203.0.113.55

But when using Docker networking, the default route is not respected and the request uses the servers primary IP as the source address:

~$ docker run --rm curlimages/curl -s -4 http://ifconfig.co
203.0.113.199

How can I configure Docker, preferably using docker-compose, to respect the host’s default route and use the correct IP as the source address?

Thanks, Paul :blush: