在 Debian 上部署 PostgreSQL 集群,常见方案有 主从流复制(Streaming Replication)、Patroni + etcd + HAProxy(高可用)、Pgpool-II 等。下面我按从简单到生产级给你讲。
apt update
apt install -y postgresql
编辑配置文件:
nano /etc/postgresql/16/main/postgresql.conf
listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = 1GB
nano /etc/postgresql/16/main/pg_hba.conf
host replication replicator 192.168.1.11/32 md5
创建复制用户:
su - postgres
psql
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'password';
重启:
systemctl restart postgresql
停止 PostgreSQL:
systemctl stop postgresql
清空数据目录:
rm -rf /var/lib/postgresql/16/main
基础备份:
pg_basebackup -h 192.168.1.10 -U replicator -D /var/lib/postgresql/16/main -P -R
设置权限:
chown -R postgres:postgres /var/lib/postgresql/16/main
启动:
systemctl start postgresql
✅ 从节点现在是只读副本
etcd (集群)
↓
Patroni (每个 PG 节点)
↓
HAProxy (VIP / 负载)
apt install -y etcd-server etcd-client
配置 /etc/default/etcd(略,核心是 cluster 配置)
apt install -y python3-pip
pip3 install patroni[psycopg2]
创建配置 /etc/patroni.yml(示例):
scope: pg-cluster
name: pg1
etcd:
hosts:
- 192.168.1.10:2379
- 192.168.1.11:2379
- 192.168.1.12:2379
postgresql:
listen: 0.0.0.0:5432
data_dir: /var/lib/postgresql/16/main
authentication:
superuser:
username: postgres
password: secret
启动 Patroni:
patroni /etc/patroni.yml
apt install -y haproxy
配置:
| 方案 | 自动切换 | 复杂度 | 推荐度 |
|---|---|---|---|
| 流复制 | ❌ | 低 | ⭐⭐ |
| Pgpool-II | ✅ | 中 | ⭐⭐⭐ |
| Patroni | ✅✅ | 高 | ⭐⭐⭐⭐⭐ |
我可以给你完整可复制的部署脚本。