I have two Ubuntu servers:

  • Server 1 (IP: is online and connect to two network interface (internal, public)

  • Server 2 (IP: with no public access (internal)

I am trying to use server1 as a default gateway for server2, and this is what I've done:

# on online server (Jumpbox)
iptables -t nat -A POSTROUTING -s ! -d -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward

# On offline server
route add default gw

Docker is installed on both (

They can PING each other, but from server2 it is not possible to PING Google.

  • try this on jumpbox: iptables -t nat -A POSTROUTING -o public_internet_interface -j MASQUERADE Sep 12, 2021 at 8:06
  • @MartynasSaint I will get error when I add the interface name No ... by that name
    – GeoCom
    Sep 12, 2021 at 9:04
  • Fixed above issue but still no ping from offline VM.
    – GeoCom
    Sep 12, 2021 at 9:22
  • try to see if the rule is hit - iptables -vL . maybe docker puts some rules that are matched first Sep 12, 2021 at 9:25
  • yes it is there, ip range for docker is in different range
    – GeoCom
    Sep 13, 2021 at 5:47

1 Answer 1


Debian Style (the lazy way):

edit /etc/network/interfaces

iface eth0 inet static
post-up   echo 1 > /proc/sys/net/ipv4/ip_forward
post-up   iptables -t nat -A POSTROUTING -s '' -o eth0 -j MASQUERADE
post-down iptables -t nat -D POSTROUTING -s '' -o eth0 -j MASQUERADE

The Lazy Crontab Way:

edit /etc/crontab

@reboot root "echo 1 > /proc/sys/net/ipv4/ip_forward; iptables -t nat -A POSTROUTING -s '' -o eth0 -j MASQUERADE; iptables -t nat -D POSTROUTING -s '' -o eth0 -j MASQUERADE"

Bash Style:

nano /root/allow_lan_nat.sh
You have to ajust the correct LAN that fits to you which might (One Lan Subnet, Default Class C) (all Subnets of 192.168) (Default Class B) (Default Class A)

#Ajust the LAN, as above shown

#The IFACE that has Internet.
echo 1 > /proc/sys/net/ipv4/ip_forward

run bash /root/allow_lan_nat.sh

Direct answer to your question

Remind, that at i state this Answer, i dont know the Interface, so i assume ens3 s your interface that face to the internet, else update it like above

echo 1 > /proc/sys/net/ipv4/ip_forward  
iptables -t nat -A POSTROUTING -s '' -o ens3 -j MASQUERADE  
iptables -t nat -D POSTROUTING -s '' -o ens3 -j MASQUERADE  

REMIND, ens3 must be the internet facing interface so update it to your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.