How to use Node.js to make a SSH tunneling connection to a MongoDB database

…衆ロ難τιáo~ 提交于 2019-12-01 02:09:53

As mscdex mentioned ssh2 isn't a good module to use to make an ssh tunnel connection to a database. tunnel-ssh is more appropriate.

Here are the configuration options I've used :

dstPort: remote database connection port

localPort: same as dstPort, It'll be the port you'll use for your local machine

username: SSH username,

host: SSH address

dstHost: database connection url (...mongodbns.com) ,

privateKey: SSH key

Then once your tunnel is connected connect via mongoose to your localhost such as mondodb://localhost:27000 (use the localport you defined in localPort)

var server = tunnel(config, function (error, server) {
    if(error){
        console.log("SSH connection error: " + error);
    }
    mongoose.connect('mongodb://localhost:27000/');
    //...rest of mongoose connection
}

Since mongoose does not support passing in a stream to use as the underlying connection, you will have to listen on a local port (e.g. 27000) and forward incoming connections to that port over the ssh connection.

Fortunately there exists third party modules that build on ssh2 that provide this kind of functionality for you, such as tunnel-ssh. Try using one of those.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!