在Debian上搭建PostgreSQL集群,可以使用Patroni和Pacemaker来实现高可用性和故障转移。以下是详细的步骤:
首先,更新你的系统并安装必要的软件包:
sudo apt update
sudo apt install -y postgresql-13-pgdg pacemaker patroni
编辑PostgreSQL的配置文件 /etc/postgresql/13/main/postgresql.conf
和 /etc/postgresql/13/main/pg_hba.conf
。
postgresql.conf
确保以下参数设置正确:
listen_addresses = '*' # 监听所有地址
wal_level = replica # 设置为replica以支持流复制
max_wal_senders = 10 # 最大WAL发送者数量
wal_keep_segments = 64 # 保留的WAL段数量
hot_standby = on # 启用热备模式
pg_hba.conf
添加以下行以允许从其他节点进行连接:
host replication replicator 192.168.1.0/24 md5
host all all 192.168.1.0/24 md5
假设你已经有一个PostgreSQL实例在运行,你可以使用Patroni来初始化集群。
创建一个Patroni配置文件 /etc/patroni.yml
:
scope: postgres
name: postgres-cluster
namespace: /db
restapi:
listen: 0.0.0.0:8008
connect_address: 192.168.1.100 # 替换为你的主节点IP
etcd:
host: 192.168.1.101 # 替换为你的etcd节点IP
port: 2379
scheme: http
bootstrap:
dcs:
ttl: 30
loop_wait: 10
retry_timeout: 10
maximum_lag_on_failover: 1048576
postgresql:
use_pg_rewind: true
use_slots: true
parameters:
wal_level: replica
max_connections: 100
hot_standby: on
max_wal_senders: 10
wal_keep_segments: 64
synchronous_commit: off
synchronous_standby_names: '*'
hot_standby_feedback: on
max_replication_slots: 10
track_commit_timestamp: on
wal_sender_timeout: 60
max_standby_streaming_delay: 30
primary_conninfo:
dbname: postgres
user: replicator
password: your_password # 替换为你的复制用户密码
host: 192.168.1.100 # 替换为你的主节点IP
standby_conninfo:
dbname: postgres
user: replicator
password: your_password # 替换为你的复制用户密码
host: 192.168.1.101 # 替换为你的备用节点IP
使用以下命令启动Patroni:
sudo patroni /etc/patroni.yml
你可以使用以下命令来验证集群的状态:
sudo systemctl status patroni
或者访问Patroni的REST API来获取集群状态:
curl http://192.168.1.100:8008/cluster
如果你有多个备用节点,可以重复上述步骤,只需更改配置文件中的 name
和 connect_address
,并确保每个节点的IP地址不同。
确保你有一个监控系统来监控集群的健康状况,并定期检查日志文件以发现潜在的问题。
通过以上步骤,你应该能够在Debian上成功搭建一个PostgreSQL集群,并实现高可用性和故障转移。