Node.js SSH Tunneling to MongoDB using Mongoose

dstHost needs to be a hostname/IP, not a MongoDB connection string. In this particular case, you can actually omit dstHost, localHost, and localPort in this particular case because they already default to the values you're providing.


The final working config for future reference. Thanks to mscdex -- I simply needed to provide the correct dstPort and include it in my Mongo URI string (the 27017). So simple. Hope this helps.

var config = {
    username:'myusername',
    host:'my.ip.address',
    agent : process.env.SSH_AUTH_SOCK,
    privateKey:require('fs').readFileSync('/Users/myusername/.ssh/id_rsa'),
    port:22,
    dstPort:27017,
    password:'mypassword'
};

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

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

Or if you don't want to change your code, provided that you have your ssh public key on the tunnel server, you can create a tunnel via ssh on the terminal:

ssh -fNL <local_port>:<mongodb_server_hostname_or_ip>:<mongodb_server_port> <tunnel_server_user>@<tunnel_server_hostname_or_ip>

Example with made-up IPs connecting to a fake AWS EC2 AMI Linux

ssh -fNL 27000:101.202.10.20:27000 [email protected]

Now this mongoose.connect('mongodb://localhost:27000/mydbname'); works like a charm. ;)