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

发布时间 2023-10-17 19:35:37作者: CrossPython
  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. 检查是否可以正常进行远程连接。