Port forwarding through a VPS with the help of Wireguard and iptables
Context
Recently I wanted to host a Minecraft server on a network that I can not port forward with. Although this can be done with an SSH tunnel too, I believe Wireguard will give a slightly better performance overall.
I will not be going through Wireguard setup in this page, but I did cover it before here: Wireguard server and peer configuration (Archlinux / Debian / Ubuntu). Instead I will just be going through the iptables portion.
Commands
Add
# iptables -t nat -A PREROUTING -p tcp -d 123.123.123.123 --dport 25565 -j DNAT --to 10.123.123.123:25565
# iptables -A FORWARD -p tcp -d 10.123.123.123 --dport 25565 -j ACCEPT
# iptables -t nat -o wg0 -A POSTROUTING -j MASQUERADE
Delete
# iptables -t nat -D PREROUTING -p tcp -d 123.123.123.123 --dport 25565 -j DNAT --to 10.123.123.123:25565
# iptables -D FORWARD -p tcp -d 10.123.123.123 --dport 25565 -j ACCEPT
# iptables -t nat -o wg0 -D POSTROUTING -j MASQUERADE
- Change
123.123.123.123
to your external facing server's public IP address - Change
10.123.123.123
to the server's Wireguard IP address - Change all instances of
25565
to a port you wish to forward - Change
wg0
to your Wireguard interface name