温馨提示×

PostgreSQL在CentOS怎么连接

小樊
63
2026-07-09 17:23:49
栏目: 云计算

CentOS 上连接 PostgreSQL,主要取决于你是本地连接还是远程连接。下面按常见场景一步步说明。


一、确认 PostgreSQL 已安装并启动

1. 查看 PostgreSQL 是否安装

psql --version

2. 启动 PostgreSQL 服务

sudo systemctl start postgresql
sudo systemctl enable postgresql

3. 查看服务状态

sudo systemctl status postgresql

默认版本可能是 postgresql-15postgresql-14,具体取决于 CentOS 版本。


二、本地连接到 PostgreSQL(最常见)

PostgreSQL 默认会创建一个 postgres 用户。

1. 切换到 postgres 用户

sudo -i -u postgres

2. 使用 psql 连接

psql

✅ 成功后会进入:

postgres=#

3. 连接指定数据库

psql -d 数据库名

三、创建用户并允许远程连接(重点)

1. 创建数据库和用户

CREATE USER myuser WITH PASSWORD 'mypassword';
CREATE DATABASE mydb OWNER myuser;
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

四、配置 PostgreSQL 允许远程连接

1. 修改 postgresql.conf

路径示例(版本不同路径可能不同):

/var/lib/pgsql/15/data/postgresql.conf

编辑:

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

修改:

listen_addresses = '*'

2. 修改 pg_hba.conf

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

在末尾添加:

# IPv4 remote connections
host    all    all    0.0.0.0/0    md5

或只允许某个 IP:

host    all    all    192.168.1.100/32    md5

3. 重启 PostgreSQL

sudo systemctl restart postgresql

五、远程连接方式

1. 使用 psql 远程连接

psql -h 服务器IP -U myuser -d mydb

示例:

psql -h 192.168.1.10 -U myuser -d mydb

六、防火墙放行 PostgreSQL 端口(默认 5432)

CentOS 7 / 8 / Stream

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

查看端口:

ss -lntp | grep 5432

七、常见问题排查

1. psql: FATAL: password authentication failed

✅ 用户名或密码错误
pg_hba.conf 未配置 md5


2. could not connect to server

✅ PostgreSQL 未启动
✅ 防火墙未放行端口
listen_addresses 未设置


3. SELinux 问题(少见)

临时关闭测试:

sudo setenforce 0

八、总结(快速连接流程)

# 本地
sudo -i -u postgres
psql

# 远程
psql -h IP -U 用户 -d 数据库

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

  • CentOS 具体版本(7 / 8 / Stream)
  • PostgreSQL 版本
  • 本地还是远程连接

我可以给你完全针对你环境的命令

0