Connecting to an external MySQL server through an SSH tunnel

Scenario: You’re at home, and you want to connect to a mysql server on the other side of a firewall. There is a machine with ssh open on it that you can use as a gateway.

  1. On your home machine:
    ssh -L 3307:domain.name.of.mysqlserver:3306 username@domain.name.of.gatewayserver

     

    This will open a tunnel, listening on localhost:3307 and forwarding everything to mysqlserver:3306, and doing it all via the ssh service on the gateway machine.

    This example shows us specifying port 3307 on the local end of the tunnel; I did this because I run a MySQL server on my home machine, so I can’t re-use the default MySQL port.

    You’ll now have a terminal open on the gateway machine, but you don’t need it for this procedure, so set it aside.

     

  2. Now, on your local machine, execute a mysql connection like so:
    mysql -u username -p -h 127.0.0.1 -P 3307 databasename

    In other words, mysql thinks it’s connecting to localhost, but on a different port. In fact, the connection is being made securely to the remote mysql server, via the gateway machine and the local “mouth” of the ssh tunnel on your own machine. 

  3. When you’re finished with your mysql session, log out of the session on the gateway machine. That will properly close the tunnel.

About vicki

Welcome to the Sovereign Republic of Vickistan. I am the President here. Lucky me! No taxes or laws yet. Lucky you!
This entry was posted in Linux, SSH. Bookmark the permalink.