Use the
PREROUTING chain in the
nat table to rewrite destination addresses and ports, allowing external traffic to reach internal services. This technique, known as Destination NAT (DNAT), redirects packets before routing decisions are finalized. By combining this with proper forwarding rules in the
filter table, you can securely expose local servers to the internet or other networks.
Understanding the NAT Table and PREROUTING Chain
The Linux kernel’s packet filtering framework,
iptables, organizes operations into tables. The
nat table is specifically designed for Network Address Translation tasks. Within this table, the
PREROUTING chain is the critical location for modifying incoming packets. It processes packets immediately after they arrive on a network interface but before the kernel decides which local process should receive them.
When you configure port forwarding, you are essentially telling the kernel: "If a packet arrives on this specific port, change its destination IP and port to point to a different machine." This happens transparently to the sender. The original source IP remains unchanged, which is vital for maintaining stateful connections. Without this step, the internal server would never see the incoming request because the destination address would not match any of its own interfaces.
It is important to distinguish between DNAT and SNAT. While DNAT changes where the packet goes, Source NAT (SNAT) or Masquerading changes where the reply comes from. For simple port forwarding where the internal server knows how to route replies back through the gateway, DNAT alone is often sufficient. However, if the internal network uses private IP ranges that are not routable from the outside, you may need additional configuration. For a deeper dive into masquerading techniques, you might want to read
Understanding NAT Masquerading in iptables: A Comprehensive Guide.
Step-by-Step Port Forwarding Configuration
To set up port forwarding, you need two main components: a rule in the
nat table to redirect traffic, and a rule in the
filter table to allow it. Let’s assume you have a gateway server with a public IP and an internal web server at
192.168.1.50 listening on port 80. You want external users to access this server by connecting to port 8080 on the gateway.
First, add the redirection rule. Use the following command to append a rule to the
PREROUTING chain:
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.50:80
This command tells
iptables to look for TCP packets destined for port 8080. When found, it changes the destination IP to
192.168.1.50 and the destination port to 80. The traffic is then passed to the next stage of processing.
Next, you must ensure the firewall allows this forwarded traffic. Even though the packet has been rewritten, the
FORWARD chain in the
filter table still controls whether the packet is allowed to pass through the kernel. Add a rule to accept this traffic:
iptables -A FORWARD -p tcp -d 192.168.1.50 --dport 80 -j ACCEPT
Without this second rule, the default policy of your firewall (often DROP or REJECT) will block the packet after the DNAT transformation. This is a common pitfall where administrators successfully configure NAT but forget to open the forwarding path.
Enabling IP Forwarding
Port forwarding requires the Linux kernel to act as a router. By default, most distributions disable IP forwarding for security reasons. You must enable it manually. Check the current status by reading the value of
/proc/sys/net/ipv4/ip_forward:
cat /proc/sys/net/ipv4/ip_forward
If the output is
0, forwarding is disabled. To enable it temporarily, run:
echo 1 > /proc/sys/net/ipv4/ip_forward
For this change to persist across reboots, you need to modify your system’s network configuration. On systems using
sysctl, add or uncomment the following line in
/etc/sysctl.conf:
net.ipv4.ip_forward = 1
Then apply the changes using the command
sysctl -p. If IP forwarding is not enabled, your
iptables rules will appear to work, but packets will be dropped silently by the kernel before they can reach the internal host.
Handling Stateful Connections
Modern firewalls rely on connection tracking to manage state. When a packet is DNATed, the connection tracker updates its state information. However, sometimes asymmetric routing or complex network topologies can confuse the tracker. In such cases, ensuring that the
conntrack module is loaded is essential.
You can verify that connection tracking is active by checking for the
nf_conntrack module. Additionally, if you are dealing with protocols that embed IP addresses in their payload (like FTP or SIP), standard DNAT may fail. These protocols require helper modules to inspect and rewrite the inner data. For example, enabling the FTP helper allows passive FTP transfers to work correctly over NAT.
If you are setting up more complex scenarios involving multiple interfaces or specific routing policies, consider reviewing
Understanding IPTables NAT for Static LANs behind Dynamic WAN for advanced static LAN configurations.
Persisting Your Rules
Commands entered directly into the terminal are lost upon reboot. To make your port forwarding configuration permanent, you need to save the current
iptables rules. The method depends on your distribution. On Debian-based systems, you can use the
iptables-persistent package. Install it via
apt install iptables-persistent, and then save your rules using
netfilter-persistent save.
On RHEL/CentOS systems, the
iptables-services package provides a service unit. Enable it with
systemctl enable iptables and save the rules with
service iptables save. Always test your rules thoroughly before saving, as a misconfiguration can lock you out of remote management. Verify connectivity from an external host and check logs with
dmesg or
journalctl if connections fail.
Frequently Asked Questions
Why is my forwarded port not accessible from the outside?
The most common cause is that IP forwarding is disabled on the gateway. Ensure that
net.ipv4.ip_forward is set to 1. Additionally, check that your cloud provider or physical firewall is not blocking inbound traffic on the external port before it reaches the
iptables rules.
Do I need to restart the service after adding iptables rules?
No,
iptables rules take effect immediately. However, if you are using a higher-level firewall manager like
ufw or
firewalld, they may override or conflict with direct
iptables commands. It is best practice to configure the native tool rather than mixing methods.
How do I forward UDP ports instead of TCP?
The process is identical, but you must specify the protocol as UDP. Change
-p tcp to
-p udp in both the
PREROUTING and
FORWARD rules. For example, use
--dport 53 -p udp for DNS forwarding.
Can I forward multiple ports to different internal servers?
Yes, you can create multiple
PREROUTING rules. Each rule should target a different external port and redirect to a unique internal IP and port combination. Just ensure each corresponding
FORWARD rule is also added to permit the traffic.
What happens if the internal server is down?
The connection attempt will time out or be rejected depending on the client's settings.
iptables does not perform health checks; it simply forwards packets. If the internal host drops the SYN packet, the gateway will relay the rejection or timeout to the external client.