下面按最常见场景给你说明:CentOS 上的 PostgreSQL 如何连接(本地 + 远程),从安装到连接一步步来。
以 PostgreSQL 15 为例(CentOS 7/8 通用):
# 添加官方仓库
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
# 安装 PostgreSQL
sudo yum install -y postgresql15-server postgresql15-contrib
# 初始化数据库
sudo /usr/pgsql-15/bin/postgresql-15-setup initdb
# 启动并设置开机自启
sudo systemctl enable postgresql-15
sudo systemctl start postgresql-15
sudo -i -u postgres
psql
或指定数据库:
psql -d postgres
✅ 默认使用 peer 认证,不需要密码
编辑配置文件:
sudo vi /var/lib/pgsql/15/data/postgresql.conf
修改:
listen_addresses = '*'
默认是
localhost,只允许本机
编辑 pg_hba.conf:
sudo vi /var/lib/pgsql/15/data/pg_hba.conf
在末尾添加:
# IPv4 远程连接
host all all 0.0.0.0/0 md5
或指定 IP:
host all all 192.168.1.0/24 md5
sudo -u postgres psql
ALTER USER postgres WITH PASSWORD 'your_password';
sudo systemctl restart postgresql-15
sudo firewall-cmd --add-port=5432/tcp --permanent
sudo firewall-cmd --reload
iptables -I INPUT -p tcp --dport 5432 -j ACCEPT
service iptables save
psql -h 服务器IP -U postgres -d postgres
could not connect to server
✅ 检查:
listen_addresses 是否配置password authentication failed
✅ 检查:
pg_hba.conf 是否使用 md5✅ 通常是:
listen_addresses = localhostCentOS 连接 PostgreSQL = 安装 → 配置监听 → 配置 pg_hba → 放行端口 → 使用 psql 或工具连接
如果你愿意,可以告诉我:
我可以直接给你针对你环境的精确配置方案。