SSH Tunnel to Remote MySQL (Port Forwarding)

We block access to production MySQL servers over port 3306 for security reasons. Here is an example, use ssh tunnel to remote MySQL, connection string that proxies localhost port 13306 to port 3306 on the target system (port forwarding)

ssh -f -L 13306:localhost:3306 -p 10022 -N

We use a few switched to make this easier to use:

  • Use -f to force SSH to go into background just before the SSH session starts. This way you can get still be prompted for passwords but then run this in background. We like this because then we don't have to have an open terminal all the time.
  • The -L switch indicates port:host:remoteport format. In this case, listen to socket 13306 on localhost and proxy to remote host port 3306.
  • The -p switch is special. You might have to connect to SSH on a remote host on a port other than the standard 22. It is starting to become common practice to change the SSH port on remote hosts to something else for security reasons. In this example, the remote host only responds to SSH on port 10022.
  • Using -N tells SSH to NOT execute remote commands. Useful when all you want this SSH session to do is port forwarding.

To kill the tunnel:

  • Use ps -C ssh or ps | grep ssh to determine which ssh process is running your tunnel. Then kill it
  • To kill all ssh clients running on your machine (as your user), use pkill ssh


Popular posts from this blog