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

后端 未结 3 1528
栀梦
栀梦 2020-12-15 14:49

My credentials work perfectly with Robomongo but I can\'t make the connection with node.js
I have tried to make the connection using ssh2 and tunnel-ssh npm module and f

相关标签:
3条回答
  • 2020-12-15 15:06

    You can do it with official mongodb client for node

    const sshTunnelConfig = {
      agent: process.env.SSH_AUTH_SOCK,
      username: 'ec2-user',
      privateKey: require('fs').readFileSync('./path-to-ec2-key.pem'),
      host: '3.98.174.12', //IP adress of VPS which is the SSH server
      port: 22,
      dstHost: 'docdb-cluster-vmabwxueb51y.eu-central-1.docdb.amazonaws.com',
      dstPort: 27017,
      localHost: '127.0.0.1',
      localPort: 27018 //or anything else unused you want
    };
    
    
    const connectionProperties = {
      sslValidate: true,
      ssl: true,
      sslCA: [fs.readFileSync('rds-combined-ca-bundle.pem')],
      useNewUrlParser: true,
      useUnifiedTopology: true,
      authMechanism: 'SCRAM-SHA-1',
      auth: {
        user: 'docdbuser',
        password: '<PASSWORD>'
      },
      tlsAllowInvalidHostnames: true,
      tlsAllowInvalidCertificates: true,
    };
    
    tunnel(sshTunnelConfig, async (error, server) => {
      if (error) {
        console.log('SSH connection error: ', error);
      }
      
       const MongoClient = require('mongodb').MongoClient;
       const client = MongoClient.connect('mongodb://localhost:27018/', propertiesConnection,
        function(err, client) {
          if(err)
            throw err;
    
          //Specify the database to be used
          db = client.db('database-name');
    
          //Specify the collection to be used
          col = db.collection('collection-name');
    
          //Insert a single document
          col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
            //Find the document that was previously written
            col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
              //Print the result to the screen
              console.log(result);
    
              //Close the connection
              client.close()
            });
          });
        });
      
    });

    0 讨论(0)
  • 2020-12-15 15:21

    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.

    0 讨论(0)
  • 2020-12-15 15:31

    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
    }
    
    0 讨论(0)
提交回复
热议问题