简体   繁体   中英

Node.js connecting through ssh

I have a node.js server that works but needs to be set up for ssh connections:

var mysql = require('mysql')
var io = require('socket.io').listen(3000)
var db = mysql.createConnection({

    host: 'hostname',
    user: 'username',
    password: '12345',
    database: '12345',
    port: 3306,
    socket: '/var/run/mysqld/mysqld.sock' 
})

db.connect(function(err){
    if (err) console.log(err)
})

I'm aware that there are ssh npm libraries for this purpose, however the options available (ssh2, node-sshclient, etc) appear to deal with pretty intricate features that may overcomplicate things. I'm looking for the simplest way to connect to my mysql db through ssh. What would be the best way to accomplish this?

If you are running a linux/unix system do the following:

Connect to your mysql server via ssh and proxy the mysql port (default is 3306) via this ssh tunnel.

This works as follows:

1 Type in screen (to start a screen session which is permanent even if the shell gets closed).

2 Type into screen shell:

ssh -L 3306:127.0.0.1:3306 your_servers_domain_or_ip -lyour_login_name

3 Enter your ssh password / or use a PKI auth to avoid manual steps

4 Done... now it's possible to connect MySQL like you would do when it's installed on the same machine as your application.

Connect to MySQL from node.js like below:

var db = mysql.createConnection({
    host: '127.0.0.1', // Important to connect to localhost after connecting via ssh in screen
    user: 'username',
    password: '12345',
    database: '12345',
    port: 3306
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM