在 CentOS 上配置 PostgreSQL 远程访问,一般分为以下几个步骤(以 CentOS 7/8 + PostgreSQL 12/13/14 为例,其他版本类似):
# 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.confsudo vi /var/lib/pgsql/14/data/postgresql.conf
找到并修改:
listen_addresses = '*'
或指定 IP:
listen_addresses = 'localhost,192.168.1.100'
✅ 默认是 localhost,只允许本地访问。
pg_hba.confsudo 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:免密(不推荐生产环境)sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload
查看:
sudo firewall-cmd --list-ports
sudo -u postgres psql
ALTER USER postgres WITH PASSWORD 'StrongPassword123';
\q
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"
listen_addresses 是否修改ALTER USER 用户名 WITH PASSWORD '新密码';
sudo setsebool -P httpd_can_network_connect_db 1
✅ 不要使用 0.0.0.0/0
✅ 使用专用数据库用户
✅ 启用 SSL
✅ 限制连接 IP
✅ 定期更新 PostgreSQL
如果你愿意,可以告诉我:
我可以给你 更精确的配置方案。