How to set iptables to access MySQL?

The most immediate problem is that your NAT rule applies only to traffic destined for 127.0.0.1 but not coming in the loopback interface. Pretty much by definition, there won't be any such traffic. Remove the -d 127.0.0.1 from your PREROUTING rule.

Your second problem is that mysqld is only listening on the loopback interface. You'll need to get it to listen on the external NIC as well, if you want to talk to an external system. I don't, offhand, know how to do that; but you want the output from netstat to look more like

tcp      0    0 0.0.0.0:3306              0.0.0.0:*                 LISTEN      

Your third problem will be that adding a NAT rule for port-forwarding doesn't implicitly punch that forwarded traffic through the firewall. Having redirected incoming traffic on TCP/33306, you'll still need to allow the resulting redirected traffic through the INPUT chain, with something like

iptables -I INPUT 8 -p tcp --dport 33306 -s a.b.c.d -j ACCEPT

where a.b.c.d is the IP address of the server you want to be able to so communicate.

Re-edit: OK, you've decided that mysqld can only bind to localhost, but you're willing to get rid of the 33306/3306 distinction, and have the incoming client connect to port 3306.

That given, I think you have a problem; we can't use SNAT to rewrite the packets as if they came from localhost, because the traffic isn't leaving the box, so the packets won't pass through the nat table's POSTROUTING chain, which is the only place SNAT is a valid target. I don't think you can easily do this with iptables, and that either an SSH connection or a VPN which provides logical interfaces, such as OpenVPN, will be needed; sorry.


I found out that it's not a good idea to mess up things like I tried before and changed etc/mysql/my.cnf to fit a normal setup like:

# bind to all ip's
bind to 0.0.0.0

I also restricted the connections for port 3306 to an IP:

iptables -I INPUT -i eth0 -p tcp --dport 3306 --src xxx.x.x.xx -j ACCEPT

Drop all traffic to that port that is not allowed:

iptables -I INPUT -i eth0 -p tcp --dport 3306 -j DROP

If someone has a better and more secure way to get it done please let me know.