Created
May 15, 2021 20:22
-
-
Save jeffcav/09f73f2d89fc88cc79f9d465e73c667e to your computer and use it in GitHub Desktop.
NAT docker containers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Enable ip forwarding in the host | |
sudo bash -c 'echo 1 > /proc/sys/net/ipv4/ip_forward' | |
# Create WAN 10.0.0.0/24 and LAN 192.168.66.0/24 networks | |
docker network create --driver bridge --subnet 10.0.0.0/24 --attachable wan | |
docker network create --driver bridge --subnet 192.168.66.0/24 --attachable --gateway 192.168.66.254 lan | |
# Create hosts and router | |
## Create the 'wan-host' and connect to the WAN network | |
docker run -itd --rm --ip 10.0.0.10 --network wan --name wan-host ubuntu | |
## Create the 'lan-host' and connect to the LAN network with additional capabilities | |
docker run -itd --rm --ip 192.168.66.2 --network lan --name lan-host --cap-add=NET_ADMIN --cap-add=NET_RAW ubuntu | |
## Create the 'lan-router' and connect to both LAN and WAN networks with additional capabilities | |
docker run -itd --rm --ip 192.168.66.1 --network lan --name lan-router --cap-add=NET_ADMIN --cap-add=NET_RAW ubuntu | |
docker network connect --ip 10.0.0.101 wan lan-router | |
# Check that 'lan-host' CANNOT ping 'wan-host' | |
docker exec lan-host bash -c "apt update && apt install -y iproute2 iputils-ping" | |
docker exec lan-host ping -c 4 10.0.0.10 | |
# Configure 'lan-router' to perform NAT from LAN to WAN networks | |
docker exec lan-router bash -c "apt update && apt install -y iptables" | |
docker exec lan-router iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE | |
# Configure 'lan-host' to have 'lan-router' as a gateway to the WAN network | |
docker exec lan-host ip route add 10.0.0.0/24 via 192.168.66.1 dev eth0 | |
# Check that 'lan-host' CAN ping 'wan-host' | |
docker exec lan-host ping -c 4 10.0.0.10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment