Skip to content

🔀 NAT Configuration

What is NAT?

NAT (Network Address Translation) is like a hotel front desk — people from outside call the front desk (public IP), and the front desk connects them to a room number (internal IP). The outside world doesn't know your real room number.

TypeFull NamePurposeAnalogy
SNATSource Address TranslationInternal machines access the internet (change source IP)Using the hotel address when sending a package
DNATDestination Address TranslationExternal access to internal services (change destination IP)Front desk forwards calls to your room
MASQUERADEDynamic SNATScenarios where IP changes, like dial-up connectionsUsing a temporary business card

Enable IP Forwarding

bash
# Enable temporarily
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null

# Enable permanently
echo "net.ipv4.ip_forward = 1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

SNAT Configuration (Internal Servers Sharing a Public IP)

bash
# Assumptions:
# - Gateway server has two NICs: eth0 (public 203.0.113.1), eth1 (internal 192.168.1.1)
# - Internal machine 192.168.1.100 needs internet access

# Configure SNAT on the gateway server
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 203.0.113.1

# If the public IP is dynamic (DHCP/PPPoE), use MASQUERADE
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE

DNAT Configuration (Port Forwarding)

bash
# Forward external port 8080 to internal 192.168.1.100:80
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80

# Allow forwarding via FORWARD chain
sudo iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPT

# Forward external port 3306 to a database server
sudo iptables -t nat -A PREROUTING -p tcp --dport 3306 -j DNAT --to-destination 192.168.1.200:3306
sudo iptables -A FORWARD -p tcp -d 192.168.1.200 --dport 3306 -j ACCEPT