Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js connecting through ssh

Tags:

node.js

mysql

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?

like image 640
Troy Griffiths Avatar asked Jul 10 '14 23:07

Troy Griffiths


People also ask

How do I run node js in PuTTY?

Install Node.js through PuTTYOpen PuTTY to launch the configuration screen. Here, you should fill out the following fields: Host Name: the IP of the server; Port: your server's port (22 by default);


1 Answers

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
});
like image 163
Bernhard Avatar answered Sep 29 '22 19:09

Bernhard