Simple, Easy NAT / PORT FORWARDING for IPTABLES (Ubuntu)

These instructions assume:

  • This is a dedicated firewall performing no other activities other than blocking and routing.
  • You have 2 network cards enabled and properly configured — one facing the public Internet, the other facing a private LAN using a non-routable IP range.
  • eth0 = public internet
  • eth1 = private LAN
  • your existing IPTABLES rules are ordered correctly (i.e. Make sure you don’t have a default DROP rule above any of these that you’re going to create below).

If this instruction helped you, I’d love to know. Leave a comment at the tone.

First, NAT’ing

Passing traffic from your private LAN out through the firewall and back using NAT

If you haven’t done it already, forwarding needs to be enabled in the kernel…

sudo echo 1 > /proc/sys/net/ipv4/ip_forward


sudo vi /etc/sysctl.conf
#uncomment this line


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

Don’t forget to save, or it won’t stick…

sudo service iptables-persistent save

then… just in case

sudo iptables-save > ~/iptables-rules.fw

Port Forwarding

Forwarding requests from the Internet through the firewall to some other server on your private network.

sudo iptables -I FORWARD -p tcp -i eth0 -d <private LAN server IP> --dport <inbound port> -j ACCEPT
sudo iptables -t nat -A PREROUTING -p tcp -i eth0 -d <Firewall Public IP> --dport <Inbound Port> -j DNAT --to-destination <private LAN server IP>:<Port where service runs>

Don’t forget to save

Other useful stuff:

list line numbers when you need to remove a specific rule from a table

sudo iptables -L --line-numbers

list the rules in the “nat” table (which is not listed by default when you run the “-L” switch)

sudo iptables -t nat -L

Add a new rule to the bottom of the table

sudo iptables -A INPUT -i eth1 -j ACCEPT

Insert a rule at the top of the table

sudo iptables -I INPUT -i eth1 -j ACCEPT

Save the rules using the service iptables-persistent
sudo service iptables-persistent save

One thought on “Simple, Easy NAT / PORT FORWARDING for IPTABLES (Ubuntu)”

Leave a Reply

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