Use Ubuntu as a Router with NAT
Setting Up Ubuntu as a Network Router with NAT
This guide explains how to configure an Ubuntu server to function as a router with Network Address Translation (NAT), allowing devices on a private network to access the internet through a single public IP address.
Network Interface Configuration
You’ll need two network interfaces:
- eth0: External/Internet-facing interface
- eth1: Internal/Private network interface
Configure Network Interfaces
Edit the network interfaces configuration file:
1
sudo nano /etc/network/interfaces
Add the following configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# The loopback network interface
auto lo
iface lo inet loopback
# The External network interface
auto eth0
#iface eth0 inet dhcp
iface eth0 inet static
address 10.6.26.67
netmask 255.255.255.0
gateway 10.6.26.254
dns-nameservers 10.6.26.61
# The Internal network interface
auto eth1
#iface eth1 inet dhcp
iface eth1 inet static
address 192.168.0.254
netmask 255.255.255.0
Apply Network Configuration
Bring up the internal interface:
1
2
sudo ifup eth1
sudo ifconfig
Enable IP Forwarding
Temporary Forwarding (Current Session)
To enable forwarding immediately:
1
sudo echo "1" > /proc/sys/net/ipv4/ip_forward
Permanent Forwarding (Persists After Reboot)
Edit the sysctl configuration file:
1
sudo nano /etc/sysctl.conf
Find and uncomment this line:
1
net.ipv4.ip_forward=1
Apply the changes:
1
sudo /etc/init.d/procps restart
Warning: Do not restart networking over SSH as it will disconnect your session. If you must restart networking, do it from a local console.
Configure NAT with iptables
Set up the necessary iptables rules for NAT:
1
2
3
4
5
6
7
8
# Enable NAT
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# Allow established connections
sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
# Allow outgoing connections from internal network
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
Make iptables Rules Persistent
Save the current iptables configuration:
1
sudo iptables-save > /etc/iptables.rules
To load these rules at boot time, create a new file:
1
sudo nano /etc/network/if-pre-up.d/iptables
Add the following content:
1
2
#!/bin/sh
/sbin/iptables-restore < /etc/iptables.rules
Make the script executable:
1
sudo chmod +x /etc/network/if-pre-up.d/iptables
Testing the Configuration
From a device on the internal network:
- Set the gateway to your Ubuntu router’s internal IP (192.168.0.254)
- Try to ping an external address (e.g., 8.8.8.8)
- Try to access a website
Troubleshooting
If devices on the internal network can’t access the internet:
- Verify IP forwarding is enabled:
1
cat /proc/sys/net/ipv4/ip_forward
Should return
1
- Check iptables rules:
1 2
sudo iptables -L -v sudo iptables -t nat -L -v
- Ensure both network interfaces are up:
1
ip a
- Verify DNS resolution:
1
ping -c 4 google.com