Clean and efficient mysql ssh tunneling (on linux)
ssh -L 3307:localhost:3306 <user>@<remotehost> -f sleep 10; mysql -u <mysqluser> -p -P3307 -h 127.0.0.1
- ssh -L 3307:localhost:3306 –> create a 3307 listening port locally that will be forwarded to a 3306 port on the other end of the ssh tunnel
- <user>@<remotehost> –> user allow to connect via ssh on the remote host
- -f –> go in background
- sleep 10 –> will execute the sleep 10 command (sleep 10 sec) on the remote host ans then close … unless the tunnel is in use (and a child proc is created) which is the case with the final
- ; mysql -u <mysqluser> -p -P3307 -h 127.0.0.1 –> mysql connecto with user <mysqluser> via port 3307 on the localhost BUT passing by TCP (‘127.0.0.1′) instead of named pipe (when using ‘localhost’)
Pay attention to the 127.0.0.1 especially when you have this kind of error:
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)
References:
- http://www.g-loaded.eu/2006/11/24/auto-closing-ssh-tunnels/
-
http://highspeedrails.com/Support/Howto/sshTunnelHowto


