温馨提示×

CentOS如何配置PostgreSQL远程

小樊
57
2026-07-09 17:33:50
栏目: 云计算

CentOS 上配置 PostgreSQL 远程访问,一般分为以下几个步骤(以 CentOS 7/8 + PostgreSQL 12/13/14 为例,其他版本类似):


一、安装 PostgreSQL(如已安装可跳过)

# PostgreSQL 官方源(以 14 为例)
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo dnf install -y postgresql14-server postgresql14-contrib

# 初始化数据库
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb

# 启动并设置开机自启
sudo systemctl enable postgresql-14
sudo systemctl start postgresql-14

二、修改 PostgreSQL 监听地址

1️⃣ 编辑 postgresql.conf

sudo vi /var/lib/pgsql/14/data/postgresql.conf

找到并修改:

listen_addresses = '*'

或指定 IP:

listen_addresses = 'localhost,192.168.1.100'

✅ 默认是 localhost,只允许本地访问。


三、配置允许远程连接的客户端

2️⃣ 编辑 pg_hba.conf

sudo vi /var/lib/pgsql/14/data/pg_hba.conf

在文件末尾添加:

# IPv4 远程访问
host    all             all             0.0.0.0/0               md5

或限制 IP 段(推荐):

host    all             all             192.168.1.0/24          md5

说明:

  • md5:使用密码认证
  • trust:免密(不推荐生产环境)

四、开放防火墙端口(默认 5432)

CentOS 7 / 8

sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload

查看:

sudo firewall-cmd --list-ports

五、设置 PostgreSQL 用户密码

sudo -u postgres psql
ALTER USER postgres WITH PASSWORD 'StrongPassword123';
\q

六、重启 PostgreSQL 服务

sudo systemctl restart postgresql-14

七、测试远程连接

在远程机器上:

psql -h 服务器IP -U postgres -d postgres

或:

psql "host=192.168.1.100 port=5432 user=postgres password=StrongPassword123 dbname=postgres"

八、常见问题排查

1️⃣ 连接被拒绝

  • listen_addresses 是否修改
  • 防火墙是否放行 5432
  • PostgreSQL 是否重启

2️⃣ 密码错误

ALTER USER 用户名 WITH PASSWORD '新密码';

3️⃣ SELinux 问题(少见)

sudo setsebool -P httpd_can_network_connect_db 1

九、安全建议(生产环境)

✅ 不要使用 0.0.0.0/0
✅ 使用专用数据库用户
✅ 启用 SSL
✅ 限制连接 IP
✅ 定期更新 PostgreSQL


如果你愿意,可以告诉我:

  • ✅ CentOS 版本
  • ✅ PostgreSQL 版本
  • ✅ 是云服务器还是本地虚拟机

我可以给你 更精确的配置方案

0