MySQL connection over SSH tunnel - how to specify other MySQL server?

Solved it! The thing was to connect to the correct server when creating the tunnel itself - should've seen that one coming.

ssh -f [email protected] -L 3307:mysql1.example.com:3306 -N

Then mysql -h 127.0.0.1 -P 3307 worked as intended. :)


I got a nice blog about how to connect to MySQL using SSH tunnel. It is very well explained here.

The command to connect to SSH tunnel:

ssh -L [listening port]:[REMOTE_MYSQL_HOST]:[REMOTE_MYSQL_PORT] [SSH_USER]@[SSH_HOST]

The command to connect to MySQL:

localhost:[listening port]

When you don't have direct access to mysql-server, you use jump-server.

From your machine, you connect(ssh) to jump-server and from there you connect to your mysql-server.

This can be avoided by using ssh- tunneling.

Suppose your

       jump server is `jump-ip`
       mysql server is `mysql-ip`
       your machine is `machine-ip`

Just open ssh client(Putty in windows or terminal in linux/ios).

Type:

    ssh -L [local-port]:[mysql-ip]:[mysql-port] [jump-server-user]@[jump-ip]

After this, you can use your localhost and local-port to access mysql-server on the remote machine directly.

Eg. Your Jdbc url to access mysql database, in that case, will be

jdbc:mysql://localhost:[local-port]/[database-name]

For Windows Users, Using Putty to connect to remote MySQL Server via Tunneling

Step1: Enter your Jump server Host/IP in the session tab Step1

Step2: Go to SSH tab--> Tunnels: Enter Your MySQL server HostName: Port as destination and Source port as your local port where you want to tunnel that service and click on Add Step2

Step3: Go back to Session tab and click on Open and Enter your credentials, if it is Username/Password based.

And use same credential as mentioned above:

jdbc:mysql://localhost:[local-port]/[database-name]