Sunday, May 6, 2018

To connect to a remote MySQL Server via an SSH Tunnel

A SSH tunnel is a exactly as the name suggests, a tunnel over SSH on which we'll forward a specific port. The port will be accessible on your local machine, but will be automatically forwarded to the remote machine so it appears as if you're remote service (MySQL in this case) is actually local.

To connect to a remote MySQL Server via an SSH Tunnel:

$ ssh -i ubun-exp.pem -p 22 -L 127.0.0.1:3308:127.0.0.1:3306 username@example.com
$ mysql -u root -p -P 3308 -h 127.0.0.1

Note: The command above will open a pseudo terminal.

Note: You have to specify host with -h and put 127.0.0.1 instead of localhost since mysql will try to connect to the local MySQL socket on your computer instead of the TCP connection via port 3306.

If you only want to create a tunnel you can use the -NnT option:

$ ssh -i ubun-exp.pem -p 22 -NnT -L 127.0.0.1:3308:127.0.0.1:3306 username@example.com

Note: -N wich will disable the ability to execute a remote command.
Note: -n will prevent reading from stdin.
Note: -T will disable the pseudo-terminal allocation.

Reference: https://hostpresto.com/community/tutorials/how-to-connect-to-a-remote-mysql-server-via-an-ssh-tunnel/

No comments: