温馨提示×

CentOS怎么设置PostgreSQL

小樊
36
2026-07-21 10:13:32
栏目: 云计算

下面以 CentOS 7 / 8 / Stream 为例,给你一套从安装到基本配置的完整 PostgreSQL 设置流程(以 PostgreSQL 14 为例,其他版本类似)。


一、安装 PostgreSQL

1️⃣ 添加 PostgreSQL 官方 yum 源(推荐)

CentOS 默认仓库版本较旧,建议使用官方源。

# 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 7
sudo yum install -y postgresql14-server postgresql14-contrib

# CentOS 8 / Stream
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
sudo systemctl status postgresql-14

四、设置 PostgreSQL 管理员密码

PostgreSQL 默认使用 peer 认证,先切换用户:

sudo -i -u postgres
psql

在 psql 中修改密码:

ALTER USER postgres WITH PASSWORD 'StrongPassword123';
\q
exit

五、配置远程访问(可选)

1️⃣ 修改 postgresql.conf

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

找到并修改:

listen_addresses = '*'

2️⃣ 修改 pg_hba.conf

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

在末尾添加:

# IPv4 remote
host  all  all  0.0.0.0/0  md5

3️⃣ 重启 PostgreSQL

sudo systemctl restart postgresql-14

六、开放防火墙端口(如果启用了 firewalld)

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

七、测试连接

psql -h 127.0.0.1 -U postgres -d postgres

八、常用管理命令

功能 命令
查看状态 systemctl status postgresql-14
重启 systemctl restart postgresql-14
进入数据库 sudo -u postgres psql
查看数据库 \l
切换数据库 \c dbname

九、不同版本快速对照

PostgreSQL 版本 服务名
12 postgresql-12
13 postgresql-13
14 postgresql-14
15 postgresql-15

如果你需要:

  • 指定版本
  • 主从复制
  • 生产环境安全配置
  • Docker 方式部署

可以直接告诉我你的 CentOS 版本 + PostgreSQL 版本 + 使用场景,我可以给你更精确的方案。

0