connecting to postgres via ssh on nodejs

Viewed 1313

I have a connection on DBeaver using an ssh tunnel as follows:

sshHostname;
sshPort;
sshUser;
sshPassword;

on the actual connection to the database I have:

dbHost;
dbPort;
dbName;
dbUsername;
dbPassword;

my node js code looks something like this:

const { Pool, Client } = require('pg')
const ssh2 = require('ssh2');

const dbServer = {
    host: dbHost,
    port: dbPort,
    database: dbName,
    username: dbUser,
    password: dbPassword
}

var c = new ssh2();

c.connect({
    host: sshHostname,
    port: 22,
    username: sshUser,
    password: sshPassword
});

c.on('ready', function () {
    c.forwardOut(sshHostname, '22', dbHost, dbPort , function(err, data) {
        const client = new Client({
            host: 'localhost',
            port: dbPort,
            database: dbName,
            user: dbUser,
            password: dbPassword,
        })
        client.connect(function (err) {
            if (err) {console.log(err)}
            else {console.log('connected...')}
        });
        client.end();
    })
});

I get the following error:

Error: connect ECONNREFUSED 127.0.0.1:dbPort
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1133:16) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: dbPort
}

I tried various configurations and various libraries with no success.

do you have any idea how to connect via nodejs to a database over a tunnel?

I have a feeling that I am actually not connecting to the ssh tunnel.

0 Answers
Related