Connect to MySQL using SSH Tunneling in node-mysql

2019-05-02 11:37发布

问题:

When using the node-mysql npm package, is it possible to connect to the MySQL server using a SSH key instead of a password?

回答1:

I got this exact system working today and it should have taken 10 minutes but I wasted 5 hours on a dumb bug I wrote (which was a direct result of me trying too hard to do it in 5 minutes).

You can do the SSH tunnel component completely independently, and then point node-mysql (or any other sql client...) to your DB by using TCP tunneled over SSH.

Just set up your SSH tunnel like this

ssh -N -p 22 sqluser@remoteserverrunningmysql.your.net -L 33306:localhost:3306

Leave that going in the background (see articles like this for more in depth info).

Then just send any MySQL client to port 33306 on localhost. It will actually connect as though you are on your remote server and using port 3306.



回答2:

Thanks so much Steve your answer help me alot. just to make it clearer use

ssh -f user@personal-server.com -L 2000:personal-server.com:25 -N

The -f tells ssh to go into the background just before it executes the command. This is followed by the username and server you are logging into. The -L 2000:personal-server.com:25 is in the form of -L local-port:host:remote-port. Finally the -N instructs OpenSSH to not execute a command on the remote system

To connect to mongo use whatever port you set as Local port (in this case the port is 2000)

For example let's say I want to connect on a remote server with IP 192.168.0.100 and mongo is running on port 27017.

Assume a user called elie with password eliepassword has access to ssh on port 22 I will have to do this First run on the terminal the following :

ssh -f elie@192.168.0.100 -L 2002:127.0.0.1:27017 -N

In my mongo connection I will do :

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:2002/mydatabase');

module.exports = mongoose.connection;

I hope this makes it clear.



回答3:

As of today version v2.1.0 support secure connection over ssl. Note that your ssh keys config is not related to mysql: please see how to setup mysql secure connection for server and client