node.js - 如何使用 Node.js 和 Knex 连接到 AWS EC2 实例内的 postgresql 数据库

标签 node.js postgresql amazon-web-services ubuntu amazon-ec2

我在 AWS 上租用了一个 Ubuntu 16.xx 的 EC2 实例并在其上安装了 PostgreSQL。我在 EC2 上的 PostgreSQL 中创建了一个数据库和表。现在我正在尝试使用 knex 通过本地 Node.js 项目连接到数据库并从数据库中获取数据。 .

我已经从任何地方启用了端口 5432 到 IP 的入站规则。

但是,它返回如下错误消息:

Error: connect ECONNREFUSED 13.229.xxx.xxx:5432
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1142:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '13.229.xxx.xxx',
  port: 5432
}

我要怎么修?我需要安装和实现反向代理吗?如果是这样,我该如何设置?我知道 AWS 上有 RDS,但我需要使用 EC2 来实现它。

以下是我的一些代码:

这是knex设置,我已经安装了 pg。与本地数据库的连接成功。但是当我将主机切换到公共(public) IP/私有(private) IP/ec2-13-229-xxx-xxx.ap-southeast-1.compute.amazonaws.com 时。它们都返回上述错误消息。
development: {
        client: 'postgresql',
        connection: {
            host: '13.229.xxx.xxx',
            database: 'project2',
            user: 'postgres',
            password: 'postgres',
            port: 5432,
        },
        pool: {
            min: 2,
            max: 10,
        },
        migrations: {
            tableName: 'knex_migrations',
        },
    },

这是我用来连接服务器的 Node.js 代码。一个很简单的,只是为了测试连接。
const express = require('express');
const hbs = require('hbs');
const app = express();
const knexConfig = require('./knexfile')['development'];
const knex = require('knex')(knexConfig);

let query = knex.select('*').from('users');

query
    .then((data) => {
        console.log(data);
    })
    .catch((err) => console.log(err));

This is my firewall setting which is turned off

另外,我暂停了我的卡巴斯基。

This is my pg_hba.conf file

而且我不确定在哪里添加我的个人IP的权限。

最佳答案

此问题与 pg_hba.conf 相关。仅限于本地主机。

此外 postgres.conf 需要有 listen_addresses = '*' .

通过将外部访问列入白名单,可以访问数据库。

来自 this article 的额外支持.

关于node.js - 如何使用 Node.js 和 Knex 连接到 AWS EC2 实例内的 postgresql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62279718/

相关文章:

amazon-web-services - AWS API 网关 + Lambda(非异步)+ 获取(异步)

python - AWS SAM 中的 event.json 是什么?

node.js - 使用 dropzone 发送文件时,Req.files 在服务器端未定义(使用 Express 和 Node 构建)

python - 无法从 Redshift 读取列名包含空格的数据

sql - Postgres 中的动态 UNION ALL 查询

postgresql - 检查postgis多边形数据的有效性(从shapefile导入)

amazon-web-services - CloudFormation 模板中待纠正的错误

javascript - 使用 Handlebars.compile 的问题

angularjs - 如何在 Protractor 中独立更新 Selenium 服务器?

node.js - 如何通过 mongoose 虚拟字段查询找到 MongoDB 文档?