You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS通过SSH连接PostgreSQL时遇连接拒绝错误求助

NodeJS通过SSH连接PostgreSQL时遭遇连接拒绝错误排查求助

我在使用NodeJS通过SSH连接PostgreSQL数据库时,一直收到连接拒绝错误(错误截图如下):
连接拒绝错误截图

但使用DBeaver连接时却能成功,我已尝试过tunnel-ssh、pg库,问题依然存在,以下是我使用ssh2和postgres库的代码,恳请帮忙排查问题:

const { Client } = require('ssh2');
const postgres = require("postgres");
// SSH Configuration
const sshConfig = {
  host: '143.xx.xxx.xx',
  port: 22,
  username: 'root',
  password:"*****"
};

// PostgreSQL Database Configuration
const dbConfig = {
  user: 'postgres',
  host: 'localhost', // 注释:因为用SSH隧道,这里填localhost
  database: 'postgres',
  password: '******',
  port: 30432, // 远程服务器上的PostgreSQL端口
};

// 创建SSH隧道
const sshTunnel = new Client();
async function getUsersOver(sql) {
  const users = await sql`
    select
      *
    from users
  `
  // 返回结果示例:[{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]
  return users
}
sshTunnel.on('ready', () => {
  sshTunnel.forwardOut(
    'localhost', // 本地地址
    dbConfig.port, // 本地端口(注释:写的是自动分配,但实际填了远程端口)
    dbConfig.host, // 远程地址(数据库主机)
    dbConfig.port, // 远程PostgreSQL端口
    (err, stream) => {
      if (err) throw err;

      // 通过SSH隧道创建PostgreSQL客户端
      const dbClient =  postgres({...dbConfig, stream});
      getUsersOver(dbClient)
    }
  );
});

sshTunnel.connect(sshConfig);

可能的问题点及修复方案:

  1. forwardOut参数错误
    forwardOut的前两个参数是本地要绑定的地址和端口,你现在填了localhost和远程PostgreSQL的端口30432,这会导致NodeJS尝试绑定本地30432端口,如果该端口被占用或无权限,就会触发连接拒绝。正确做法是让系统自动分配本地端口,将第二个参数改为0:

    sshTunnel.forwardOut(
      '0.0.0.0', 
      0, // 自动分配本地端口
      dbConfig.host, 
      dbConfig.port, 
      (err, stream) => {
        // ... 后续代码
      }
    );
    
  2. postgres客户端配置冗余
    当使用stream参数连接时,不需要再传入host和port,因为流已经代表了SSH隧道的连接通道。修改dbClient的创建代码:

    const { host, port, ...dbWithoutHostPort } = dbConfig;
    const dbClient = postgres({ ...dbWithoutHostPort, stream });
    
  3. 缺少错误捕获
    给SSH客户端添加错误监听,避免未处理的异常导致程序崩溃:

    sshTunnel.on('error', (err) => {
      console.error('SSH连接出错:', err);
    });
    
  4. 验证远程PostgreSQL监听地址
    确认远程服务器上的PostgreSQL配置postgresql.conf中listen_addresses是否包含localhost(因为你dbConfig里填的是localhost),如果DBeaver能连,这一步大概率没问题,但可以交叉验证。

内容的提问来源于stack exchange,提问作者Parth Mahida

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:25:24