温馨提示×

如何设置CentOS PostgreSQL

小樊
68
2026-08-05 00:23:40
栏目: 云计算

下面给你一份**在 CentOS 上安装并配置 PostgreSQL(以 CentOS 7/8 为例)**的完整流程,适合新手和常用生产环境。


一、安装 PostgreSQL

方式一:使用 CentOS 自带仓库(版本较旧)

sudo yum install -y postgresql-server postgresql-contrib

初始化数据库:

sudo postgresql-setup initdb

启动并设置开机自启:

sudo systemctl start postgresql
sudo systemctl enable postgresql

方式二(推荐):使用 PostgreSQL 官方仓库(版本更新)

以 PostgreSQL 15 为例:

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

初始化:

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

启动:

sudo systemctl start postgresql-15
sudo systemctl enable postgresql-15

二、基本配置

1️⃣ 切换到 postgres 用户

sudo -i -u postgres

进入数据库:

psql

2️⃣ 设置 postgres 用户密码

ALTER USER postgres PASSWORD 'your_password';

退出:

\q

三、允许远程访问(重点)

1️⃣ 修改 postgresql.conf

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

修改或取消注释:

listen_addresses = '*'

2️⃣ 修改 pg_hba.conf

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

末尾添加:

# IPv4 remote access
host  all  all  0.0.0.0/0  md5

⚠️ 生产环境建议限制 IP,如 192.168.1.0/24


3️⃣ 重启 PostgreSQL

sudo systemctl restart postgresql-15

四、防火墙设置

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

五、创建数据库和用户(常用)

sudo -i -u postgres
psql
CREATE DATABASE mydb;
CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

六、测试连接

本地测试

psql -h 127.0.0.1 -U myuser -d mydb

远程测试

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

七、常见问题

1️⃣ Ident authentication failed

原因:pg_hba.conf 默认使用 ident ✅ 改为 md5


2️⃣ 无法远程连接

✅ 检查:

  • listen_addresses
  • pg_hba.conf
  • 防火墙
  • SELinux(可临时关闭测试)

3️⃣ SELinux 问题(少见)

setenforce 0

八、总结(快速命令)

yum install postgresql-server
postgresql-setup initdb
systemctl enable --now postgresql
firewall-cmd --add-port=5432/tcp --permanent
firewall-cmd --reload

如果你用的是 CentOS 7 / 8 / Stream 或想配置 主从复制 / 高可用 / 性能优化,告诉我具体版本和用途,我可以给你定制一份配置方案。

0 踩