Enable external network access to Docker containers network without port mapping or adding new networks

By default, Docker creates it’s own network on the host machine, thus you cannot access containers from external networks directly. For example, I would like to access Bitwarden container with IP 172.17.0.3 directly from my LAN network workstation (172.16.3.2).

Enable forwarding mode on the Docker host:

sysctl -w net.ipv4.ip_forward=1
iptables -A FORWARD -i docker0 -o ens18 -j ACCEPT
iptables -A FORWARD -i ens18 -o docker0 -j ACCEPT

In the commands above, replace “ens18” with your network card interface.

On your LAN router, create a gateway and a static route to 172.17.0.0/24 network. Your new gateway for this static route is IP of the machine hosting Docker (in my example 172.16.20.80). Different routers have different ways of setting up gateways and routes, read the manual.

LAN (172.16.3.0/24) –> Gateway – Docker host (172.16.20.80) –> Remote Network – Docker containers (172.17.0.0/24)

Edit: 172.17.0.0/16 should be 172.17.0.0/24 for my network

You can now access containers directly from LAN network.

Keep in mind Docker has it’s own mechanisms of achieving direct access to containers without fiddling with routes. One of the ways would be to assign container to a VLAN with macvlan driver: https://s55ma.radioamater.si/2019/09/29/proxmox-ubuntu-18-04-guest-vlan-trunk-for-docker-containers/.

 

Leave a Reply

Your email address will not be published. Required fields are marked *