温馨提示×

如何安装CentOS PostgreSQL

小樊
45
2026-07-21 10:02:33
栏目: 云计算

下面给你一份在 CentOS 上安装 PostgreSQL 的完整指南,涵盖 CentOS 7 / 8 / Stream,以及常见配置步骤。


一、确认 CentOS 版本

cat /etc/centos-release

二、安装 PostgreSQL(推荐方式:官方仓库)

✅ 方式一:使用 PostgreSQL 官方 YUM 仓库(推荐)

1. 安装官方仓库

PostgreSQL 16 为例(可换成 15 / 14):

CentOS 7

sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

CentOS 8 / Stream

sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm

2. 禁用系统自带 PostgreSQL(CentOS 8+)

sudo dnf -qy module disable postgresql

3. 安装 PostgreSQL

sudo yum install -y postgresql16-server postgresql16-contrib

4. 初始化数据库

sudo /usr/pgsql-16/bin/postgresql-16-setup initdb

5. 启动并设置开机自启

sudo systemctl enable postgresql-16
sudo systemctl start postgresql-16

6. 检查运行状态

sudo systemctl status postgresql-16

三、配置 PostgreSQL

1. 切换到 postgres 用户

sudo -i -u postgres

2. 进入数据库

psql

3. 设置 postgres 用户密码

\password postgres

退出:

\q

四、允许远程连接(可选)

1. 修改 postgresql.conf

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

修改:

listen_addresses = '*'

2. 修改 pg_hba.conf

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

添加:

host  all  all  0.0.0.0/0  md5

3. 重启 PostgreSQL

sudo systemctl restart postgresql-16

4. 开放防火墙端口(默认 5432)

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

五、测试连接

psql -h localhost -U postgres

六、常见问题

❓ 找不到 service?

systemctl list-units | grep postgres

❓ 忘记 postgres 密码?

sudo passwd postgres

七、如果你需要

✅ 指定版本(12 / 13 / 14 / 15)
✅ 使用 Docker 安装
✅ 主从复制 / 高可用
✅ 中文排序 / 字符集配置

告诉我你的 CentOS 版本 + PostgreSQL 版本需求,我可以给你定制步骤。

0