4

I am trying to connect to Mongodb through ssh username/password through nodejs as below :

var mongoose = require('mongoose');
var tunnel = require('tunnel-ssh');

var config = {
username : 'xyz',
host: 'xx-xxx-xx.com',
port:22,
password:'xxx',
dstPort:27017,
localPort:27017
};

console.log(tunnel);
var server = tunnel(config, function (error, server) {

if(error){
    console.log("SSH connection error: " + error);
}
console.log(server);
mongoose.connect('mongodb://localhost:27017/myDB');

var db = mongoose.connection;
console.log(db);
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
    console.log("DB connection successful");
});
});

But I am getting error as below : DB connection error: { MongoError: connection 0 to localhost:27017 timed out

What is the issue here?

1 Answer 1

3

Probably is because you are missing the 'dstHost'in the config options.

The 'dstHost' must be the destination server url.

from official tunnel-ssh doc

 var config = {
      username:'root',
      Password:'secret',
      host:sshServer,
      port:22,
      dstHost:destinationServer,
      dstPort:27017,
      localHost:'127.0.0.1',
      localPort: 27000
    };

    var tunnel = require('tunnel-ssh');
    tunnel(config, function (error, server) {
      //.... 
    });
Sign up to request clarification or add additional context in comments.

5 Comments

I tried by adding dstHost . But I am getting the same error.
have you also added localHost:'127.0.0.1' to the options ?
Yes I tried adding localHost:'127.0.0.1' also . But getting same result.
can you connect to your local db without tunnelin ? If so then there must be some config missing with your ssh server, have a look at this thread stackoverflow.com/questions/38509995/… maybe you need a private key ?
I can connect to localdb with no errors. I dont have any private key . Through ssh username/password I am able to connect in MongoDB Compass but not from nodejs program

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.