EC2 上的 PostgreSQL 数据库:连接被拒绝

Ash*_*Liu 2 django postgresql amazon-ec2 amazon-web-services

我在同一个 VPC 中的两个 EC2 实例上设置了我的 Django 应用程序和 PostgreSQL 数据库。应用程序在子网连接到互联网网关的实例上;数据库位于具有没有 Internet 网关的子网的实例上。

应用实例的私有IP为10.0.0.164;数据库实例的私有 IP 是 10.0.1.136。

当我尝试将 Django 应用程序连接到数据库时,出现错误

无法连接到服务器:连接被拒绝
服务器是否在主机“10.0.1.136”上运行并接受端口 5432 上的 TCP/IP 连接?

但是,我在数据库实例的端口 5432 上允许入站 TCP 流量。我对托管数据库的实例的安全组规则:

入站:允许来自托管 Django 应用程序的实例的内部 IP 地址的所有端口中的所有 TCP 和 ICMP IPV4&IPV6 流量 (10.0.0.164/32)

(我的入站规则截图https://imgur.com/a/HNbrIDm

出站:允许所有端口的所有流量到任何地方

pg_hba.conf在数据库 EC2 实例上的文件:

# Database administrative login by Unix domain socket
local   all             postgres                                md5

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
host    all             all             10.0.0.164/32           trust
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   articles        postgres                                md5
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5
Run Code Online (Sandbox Code Playgroud)

我的postgresql.conf文件已将侦听地址设置为“10.0.0.164、127.0.0.1”,并将端口设置为“5432”。

我在 Django 中的数据库设置settings.py

ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'articles',
            'USER': 'postgres',
            'PASSWORD': 'password',
            'HOST': '10.0.1.136',
            'PORT': '5432',
Run Code Online (Sandbox Code Playgroud)

我还能做些什么来使数据库实例接受连接?

编辑:我的 EC2 实例运行的是 Ubuntu 16.04

编辑:这是我从sudo lsof -nP -i | grep LISTEN数据库实例上运行得到的:postgres 1823 postgres 6u IPv4 19766 0t0 TCP 127.0.0.1:5432 (LISTEN)

我跑了sudo ufw allow 5432,还是同样的错误

当我netstat -nlt在数据库实例上运行时,我没有看到端口 5432

小智 5

postgres 1823 postgres 6u IPv4 19766 0t0 TCP 127.0.0.1:5432(听)

那就是你的问题,你的 postgres 只绑定到本地主机。

通过编辑 /var/lib/pgsql/data/postgresql.conf 或 /etc/postgresql/"Version number here"/main/postgresql.conf 文件来更改 postgres 正在侦听的 IP 并更改侦听地址如下.. .

listen_addresses='127.0.0.1 10.0.1.136'
Run Code Online (Sandbox Code Playgroud)

你必须像我一样在后期版本的 postgres 中声明没有逗号的监听地址

我希望这能解决您的问题!:)