Search code examples
linuxdockerdocker-networktunmasquerade

Masquerading docker interface and host interface


I am running a docker on a host and I would like to connect a specific interface inside the docker (TUN interface) to one the host's external interfaces.

When running ifconfig inside the docker, I see 3 interfaces: eth0, lo and my_tun (tun interface). On the host, I see lo, docker0 and enp7s0 (external network). The result I seek for, is that packets that are sent on the my_tun interface will be sent to the enp7s0.

If the TUN interface was not inside a docker, I would do something like:

sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A POSTROUTING -o enp7s0 -j MASQUERADE

So my question is how to do it with a TUN interface that belongs to a docker container (preferably on Ubuntu).

Thanks in advance!


Solution

  • I solved it at last with an intermediate network. I created a docker network of type bridge and connected it to the container and the host. Then I used iptables rules inside the container to forward communication from the tun device to the network and similar rules on the host to forward communication from the network to the external interface.

    So assuming the network is named proxy_net, its docker interface is proxy_net0 and its gateway is 192.168.1.254.

    Inside the container:

    iptables -A FORWARD -i my_tun -o proxy_net0 -j ACCEPT
    iptables -A FORWARD -i proxy_net0 -o my_tun -m state --state ESTABLISHED,RELATED -j ACCEPT
    iptables -A POSTROUTING -t nat -o proxy_net0 -j MASQUERADE
    ip route replace default via 192.168.1.254 dev proxy_net0
    

    On the host:

    sudo iptables -A FORWARD -i proxy_net -o enp7s0 -j ACCEPT
    sudo iptables -A FORWARD -i enp7s0-o proxy_net -m state --state ESTABLISHED,RELATED -j ACCEPT
    sudo iptables -A POSTROUTING -t nat -o enp7s0 -j MASQUERADE