在 CentOS 上远程连接 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
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb
sudo systemctl enable --now postgresql-14
postgresql.conf找到配置文件(路径可能不同):
sudo vi /var/lib/pgsql/14/data/postgresql.conf
修改或添加:
listen_addresses = '*'
*表示监听所有网卡(或写具体 IP)
pg_hba.confsudo vi /var/lib/pgsql/14/data/pg_hba.conf
在末尾添加(示例):
# 允许所有 IP 使用密码连接
host all all 0.0.0.0/0 md5
或更安全一点(指定 IP):
host all all 192.168.1.0/24 md5
sudo systemctl restart postgresql-14
sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload
(云服务器还需在安全组放行 5432)
sudo -u postgres psql
CREATE USER remote_user WITH PASSWORD 'password';
CREATE DATABASE testdb OWNER remote_user;
GRANT ALL PRIVILEGES ON DATABASE testdb TO remote_user;
psql -h 服务器IP -U remote_user -d testdb
服务器IP5432remote_userpasswordtestdb✅ 连不上?检查:
listen_addressespg_hba.conf 是否生效如果你提供:
我可以帮你精准排错。