I’ve been doing some work involving an application that needs to query databases on separate servers however one of the servers will only accept mysql connections locally so the way round it is to forward connections from a port on one system to a port on a remote system. That way the connection to the remote database will appear as though it originated locally and be accepted.
To set up a tunneled connection you issue the following command on any client:
ssh -fNg -L 3307:127.0.0.1:3306 myuser@remotehost.com
The first command tells ssh to log in to remotehost.com as myuser, go into the background (-f) and not execute any remote command (-N), and set up port-forwarding (-L localport:localhost:remoteport ). In this case, we forward port 3307 on localhost to port 3306 on remotehost.com.
December 31st, 2008 at 9:56 am
This wouldn’t work with the default setup of MySQL or SSH (on Gentoo at least).
For the MySQL part to work, the server has to have been set-up to listen on the loopback interface. This is done by removing the ’skip-networking’ line from the [mysqld] section in my.cnf and adding a line like this:
bind-address = 127.0.0.1
For the SSH server the following options need to be set in sshd.conf for it to accept tunnelling requests:
AllowTCPForwarding Yes
GatewayPorts Yes
This one is probably a good idea so your connection doesn’t get dropped:
TCPKeepAlive Yes
December 31st, 2008 at 10:07 am
Thanks for the useful information. It worked out of the box on my service provider’s server possibly with the exception of TCPKeepAlive.