在 CentOS 上搭建 PostgreSQL 集群,需要先明确“集群”的具体目标,因为不同场景方案不同。下面我按常见用途给你分类说明,并给出主流方案 + 简要步骤。
| 需求 | 推荐方案 |
|---|---|
| 高可用(主挂了自动切换) | Patroni + etcd + PostgreSQL |
| 读写分离 / 热备 | 流复制(Streaming Replication) |
| 多主写入 | PostgreSQL 本身不支持(可用中间件) |
| 分布式数据库 | Citus / Postgres-XL |
| 负载均衡 | Pgpool-II / HAProxy |
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 postgresql14-server postgresql14
初始化(仅主节点):
/usr/pgsql-14/bin/postgresql-14-setup initdb
systemctl enable postgresql-14
systemctl start postgresql-14
编辑 postgresql.conf:
listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = 1GB
编辑 pg_hba.conf:
host replication repl 192.168.1.11/32 trust
创建复制用户:
CREATE ROLE repl LOGIN REPLICATION PASSWORD 'password';
重启主库:
systemctl restart postgresql-14
停止数据库:
systemctl stop postgresql-14
清空数据目录:
rm -rf /var/lib/pgsql/14/data/*
基础备份:
pg_basebackup -h 192.168.1.10 -U repl -D /var/lib/pgsql/14/data -P -R
启动备库:
systemctl start postgresql-14
✅ 此时已是 主从集群
etcd (3节点)
↓
Patroni (每个 PG 节点)
↓
PostgreSQL
patroni.ymlpatronictl 管理集群(这一步较复杂,如果你需要我可以给你完整配置文件 + 一步步命令)
你可以告诉我:
我可以直接给你:
✅ 可复制的配置文件
✅ 一键脚本思路
✅ 生产级架构图
你是学习用还是生产环境?