Set default gateway of container to different one than host

Hi there, I don’t have much experience with networking in Docker and I have a problem I can’t find a working solution for.

My setup is as follows: I have a ubuntu server with two network interfaces A (172.50.1.0/24) and B (192.168.178.0/24). Both networks have their own router with their own public IP. The default route/gateway of the server is network A. When I run a container, it currently grabs the default gateway of my server, which is network A, and routes all traffic through it. Due to bandwidth limitations of network A, I want some containers to use network B as their gateway to the Internet.

I have already tried to create a separate network using docker network create with the gateway and subnet parameters of network B, but with no success. I assume I also need to add some iptable rules to make it work?

Does anyone have a setup like this or a better understanding of docker networking and can assist me with this?

Thanks in advanve! :slight_smile:

I wrote about Docker networks here:

There are mentioned sources at the end of the article, but it doesn’t answer your question directly. If you want to route all container’s traffic through a specific interface, I guess you could create a bridge on the host and configure the Docker daemon to use that bridge:

  -b, --bridge string                   Attach containers to a network bridge

If you want to configure it per container, you can check this project:

Ihttps://github.com/tozd/docker-external-ip

I haven’t tried it, I just found it in a moby issue on GitHub

Since it configures iptables, I think I would try it first in a test virtual machine. If you don’t want to use it, you can at least check the source code to get some ideas.

Although it is not what you need, but in case anyone finds your question who has only one interface with multiple ip addresses, I also found an article that explain in 2017 how a Docker network could be configured to use one f the ip addresses in the outgoing packets.

2 Likes

That looks exactly like what I was looking for, Thanks! :slight_smile:
I found a temporary solution here passing the physical interface to the container which works fine, but this way each container shows up in the router as an individual device. I will give the GitHub solution a try.