0

I am trying to connect to a remote server MongoDB in Docker through ssh in Nodejs as below :

sshConfig = {
  username: 'username',
  password: 'password',
  host: 'host',
  port: 22,
  dstHost: '172.17.0.3',
  dstPort: 27017,
  localPort: 5000
};

const uri = 'mongodb://admin:password@localhost:27017/admin';

tunnel(sshConfig, async error => {
    if (error) {
      throw new Error(`SSH connection error: ${error}`);
    }

    const client = new MongoClient(uri);

    async function run() {
      try {
        // Connect the client to the server
        await client.connect();
        // Establish and verify connection
        await client.db('admin').command({ ping: 1 });
        console.log('Connected successfully to server');
      } finally {
        // Ensures that the client will close when you finish/error
        await client.close();
      }
    }
    await run().catch(console.dir);
  });

But I am getting error as below :

MongoServerError: Authentication failed. at MessageStream.messageHandler (/node_modules/mongodb/src/cmap/connection.ts:740:20) at MessageStream.emit (node:events:390:28) at MessageStream.emit (node:domain:475:12) at processIncomingData (/node_modules/mongodb/src/cmap/message_stream.ts:167:12) at MessageStream._write (/node_modules/mongodb/src/cmap/message_stream.ts:64:5) at writeOrBuffer (node:internal/streams/writable:389:12) at _write (node:internal/streams/writable:330:10) at MessageStream.Writable.write (node:internal/streams/writable:334:10) at Socket.ondata (node:internal/streams/readable:754:22) at Socket.emit (node:events:390:28) { ok: 0, code: 18, codeName: 'AuthenticationFailed' },

and I open http://localhost:5000/ by browser, it shows that:

It looks like you are trying to access MongoDB over HTTP on the native driver port.

I can connect the database via:

  1. Use MongoDB compass to connect the database via ssh
  2. Use mongo 'mongodb://admin:password@remote-host:27017/admin' in local machine terminal
  3. Use MongoClient(mongodb://admin:password@remote-host:27017/admin) in Nodejs without ssh-tunnel
  4. Use mongo 'mongodb://admin:password@localhost:27017/admin' in both remote host and remote host docker contaniner

I am sure the password is correct.

ArlenX
  • 3
  • 1
  • 3
  • Did you create the admin user in the `admin` database? See https://stackoverflow.com/questions/63754742/authentication-failure-while-trying-to-save-to-mongodb/63755470#63755470 – Wernfried Domscheit Sep 30 '21 at 06:38
  • @WernfriedDomscheit Yes, I can use MongoDB compass to connect the database via ssh, I am sure the password is correct. – ArlenX Sep 30 '21 at 21:27

0 Answers0