Node.js SSH Tunneling to MongoDB using Mongoose

前端 未结 3 1937
滥情空心
滥情空心 2021-01-02 06:05

I have two Mongo DBs. One for my dev environment, one for production as seen here from my Robomongo setup:

The production db is SSH tunneled to my Digital O

相关标签:
3条回答
  • 2021-01-02 06:09

    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.

    0 讨论(0)
  • 2021-01-02 06:30

    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");
        });
    });
    
    0 讨论(0)
  • 2021-01-02 06:32

    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 ec2-user@33.44.55.66
    

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

    0 讨论(0)
提交回复
热议问题