浏览器标题切换
浏览器标题切换end

Ubuntu下PostgreSQL开启远程访问(解决postgresql 端口不对外开放问题)

报错内容

EF Core进行迁移数据时,无法连接到服务器上的数据库。

报错原因

我们查看下数据库pgsql对应的端口 netstat -a | grep PGSQL,输出以下内容,端口为5432。

root@VM-16-4-ubuntu:/etc/postgresql/10/main# netstat -a | grep PGSQL
unix  2      [ ACC ]     STREAM     LISTENING     159539850 /var/run/postgresql/.s.PGSQL.5432

但是需要知道的是,默认情况下,PostgreSQL不开启远程连接,也就是说其服务仅监听本地网络127.0.0.1,所以造成连接失败。

解决办法

  1. 修改配置文件:sudo vim /etc/postgresql/9.5/main/pg_hba.conf,在文件中添加 host all all 0.0.0.0/0 md5

    • all :匹配任何IP地址。
    • 0.0.0.0/0:对于所有IPv4地址,允许任何ip地址以任何用户身份连接任何数据;::0/0:对于所有 IPv6 地址。
    • md5:加密方式。
      ·
  2. 修改 postgresql.conf:执行 sudo vim /etc/postgresql/9.5/main/postgresql.conf 文件,把文件中的 localhost 替代为 *

    • 文件路径可能不同电脑不一样,9.5是数据库版本号。
    • 如果找不到该文件,执行 find / -name "postgresql.conf" 找到路径。
  3. 修改 PostgreSQL 数据库 默认用户postgres的密码,修改为:用户名:postgres,密码:postgres

    • step1: 登录PostgreSQL:sudo -u postgres psql
    • step2: 修改登录PostgreSQL密码:ALTER USER postgres WITH PASSWORD 'postgres';
    • step3: \q
  4. 重启postgresql,刚刚的配置才能生效: service postgresql restart

  5. 开放防火墙端口。

    • step1: sudo apt-get install iptables
    • step2: 增加规则 iptables -I INPUT -p tcp --dport 5432 -j ACCEPT
    • step3: 保存 iptables-save
  6. 检查是否可以正常进行远程连接。

posted @ 2022-04-22 02:46  抓水母的派大星  阅读(3512)  评论(0编辑  收藏  举报