Network Address Translation (NAT) allows multiple devices to share a single public IP address. On a VPS, NAT is used for Docker networking, VPN setups, and routing traffic between private and public networks.
Types of NAT
# SNAT (Source NAT) — Changes source IP of outgoing packets
# Used for: Allowing private network hosts to access the internet
# DNAT (Destination NAT) — Changes destination IP of incoming packets
# Used for: Port forwarding, load balancing
# Masquerade — Dynamic SNAT (uses outgoing interface IP)
# Used for: When the public IP may change (DHCP)Masquerading (Most Common)
# Enable IP forwarding
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-forward.conf
# Set up masquerading
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# This allows hosts on private networks (VPN clients, containers)
# to access the internet through your serverPort Forwarding (DNAT)
# Forward port 8080 on public IP to internal server 10.0.0.5:80
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 \
-j DNAT --to-destination 10.0.0.5:80
sudo iptables -A FORWARD -p tcp -d 10.0.0.5 --dport 80 -j ACCEPT
# Forward port range
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 30000:31000 \
-j DNAT --to-destination 10.0.0.5Viewing NAT Rules
# List NAT table rules
sudo iptables -t nat -L -n -v
# List with line numbers
sudo iptables -t nat -L -n --line-numbers
# Delete a NAT rule
sudo iptables -t nat -D PREROUTING 1NAT with Docker
# Docker uses NAT automatically for container networking
# When you publish a port (-p 8080:80), Docker creates:
# 1. A DNAT rule to forward 8080 to the container IP:80
# 2. A masquerade rule for container outbound traffic
# View Docker NAT rules
sudo iptables -t nat -L -n | grep DOCKERNAT with WireGuard VPN
# In WireGuard config, PostUp/PostDown handle NAT:
[Interface]
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADETroubleshooting NAT
# Check if IP forwarding is enabled
cat /proc/sys/net/ipv4/ip_forward
# Check NAT rules are present
sudo iptables -t nat -L POSTROUTING -n -v
sudo iptables -t nat -L PREROUTING -n -v
# Trace a packet through NAT
sudo iptables -t nat -I PREROUTING -p tcp --dport 8080 -j LOG --log-prefix "NAT-PRE: "
sudo iptables -t nat -I POSTROUTING -j LOG --log-prefix "NAT-POST: "
# Check /var/log/kern.log for the logged packets