在 CentOS 上搭建 PostgreSQL 集群,常见方案有几种,取决于你的目标:高可用(HA)、读写分离、还是分布式扩展。下面我按“最常用、最稳妥”的方式给你讲,并给出可操作的步骤。
| 类型 | 说明 | 常用方案 |
|---|---|---|
| 主从复制(热备) | 一主多从,读写分离 | Streaming Replication |
| 高可用(自动故障切换) | 主挂了自动切 | Patroni + etcd + HAProxy |
| 分布式数据库 | 水平扩展 | Citus / PostgreSQL-XL |
✅ 90% 的 CentOS PostgreSQL 集群 = 流复制 + Patroni
假设:
systemctl stop firewalld
systemctl disable firewalld
# 或
firewall-cmd --add-port=5432/tcp --permanent
firewall-cmd --reload
vi /etc/hosts
192.168.1.10 pg1
192.168.1.11 pg2
dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf install -y postgresql14-server postgresql14
/usr/pgsql-14/bin/postgresql-14-setup initdb
systemctl enable --now postgresql-14
修改 postgresql.conf
listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = 1GB
修改 pg_hba.conf
host replication repluser 192.168.1.0/24 md5
创建复制用户
CREATE ROLE repluser WITH REPLICATION PASSWORD 'pwd' LOGIN;
pg_basebackup -h 192.168.1.10 -U repluser -D /var/lib/pgsql/14/data -P -R
systemctl start postgresql-14
✅ 此时已是 主从集群
yum install -y etcd
/etc/etcd/etcd.conf
ETCD_LISTEN_CLIENT_URLS="http://0.0.0.0:2379"
ETCD_ADVERTISE_CLIENT_URLS="http://pg1:2379"
pip3 install patroni[etcd]
scope: pg-cluster
name: pg1
restapi:
listen: 0.0.0.0:8008
connect_address: pg1:8008
etcd:
hosts: pg1:2379,pg2:2379
bootstrap:
dcs:
ttl: 30
postgresql:
use_pg_rewind: true
postgresql:
listen: 0.0.0.0:5432
data_dir: /var/lib/pgsql/14/data
authentication:
superuser:
username: postgres
password: pass
patroni /etc/patroni.yml
✅ 自动选主 + 故障切换
yum install haproxy
用 HAProxy 做 5432 端口统一入口
patronictl list
patronictl switchover
pg_ls_replication_slots()
如果你愿意,我可以:
你现在是测试还是生产环境?