iptables Port Forwarding

Forward a port to another machine with DNAT, or redirect it to a different port on the same server. Enter the details and copy the commands in the right order. IPv4 only.

Only needed when the destination answers via another gateway, or sits on the same network as the client. Leave it off if this server is the destination's default gateway, so the destination sees the real client address.

1. Let the server forward packets

Linux drops forwarded packets unless net.ipv4.ip_forward is 1. The second line keeps the setting after a reboot.

2. Add the rules

The nat rule rewrites the destination in PREROUTING, before the routing decision. That is why the FORWARD rule matches the new address and port, not the public ones, and why in redirect mode the INPUT rule uses the local port. See iptables tables and chains explained. Masquerade (source NAT) is only needed when the destination's replies would not travel back through this server, for example when it uses a different default gateway or is on the same network as the client. The rule matches only connections that were DNAT'ed to the destination. See MASQUERADE vs SNAT for the difference.

3. Check it

The packet counters in the -v output rise when traffic matches. Test from another machine: a connection started on the server itself does not pass PREROUTING.

Make it permanent

Rules and the sysctl setting must be saved separately, see saving iptables rules. On a cloud server the provider firewall must also allow the public port, for example on Oracle Cloud.

Undo

Each -D line removes the first rule that matches exactly. If you already had an identical rule, list the chain first.

Nothing happens? Check these

IP forwarding is off. cat /proc/sys/net/ipv4/ip_forward must print 1.
FORWARD blocks it. The ACCEPT rules must sit above any REJECT or DROP rule, and a default DROP policy needs the established-connections rule.
Replies take another route. Add masquerade, or set this server as the destination's default gateway.
The destination's own firewall must allow the destination port.

FAQ

How do I forward a port with iptables?

Enable IP forwarding, add a DNAT rule in the nat table's PREROUTING chain with --to-destination IP:port, and allow the translated traffic in the FORWARD chain.

What is the difference between DNAT and REDIRECT?

DNAT sends traffic to any address and port. REDIRECT is a special case that sends it to a port on the same machine.

Why does forwarding fail when I test from the server itself?

Locally generated packets do not pass PREROUTING. Test from another machine, or add an OUTPUT rule for local traffic.

© PacketUtils. Tools run in your browser. Review every command before using it in production.HomeAboutContactPrivacy PolicyGitHub