Forward ports in Ubuntu Server 12.04 using ufw

We needed to forward port 3307 to port 3306 to get around a new company wide firewall restriction blocking access to port 3306 (our MySQL server). It was a pain to find how to get port forwarding working in Ubuntu Server 12.04, which uses “ufw” as a front end to “iptables”. I couldn’t get it working without specifically forwarding to my IP, which I shouldn’t need to do (but at least it works).

This will forward port 3307 to 3306 so you can connect to your.ip.add.ress:3307 and have it automatically connect to a server (such as MySQL) on port 3306.

To do this you need “ufw” to be enabled, which you can check with “sudo ufw status”.

Make sure the ports you need are allowed:

sudo ufw allow 3307

Now open up “/etc/ufw/before.rules”:

sudo nano /etc/ufw/before.rules

Go to the bottom of the file and put:

# nat Table rules
*nat
:PREROUTING ACCEPT [0:0]
-A PREROUTING -i eth0 -p tcp -m tcp -d your.ip.add.ress –dport 3307 -j DNAT –to-destination your.ip.add.ress:3306
COMMIT

Restart “ufw” to make sure everything worked ok:

sudo ufw disable
sudo ufw enable

Now when you connect to port 3307 it will forward to 3306.