在Linux上搭建PostgreSQL集群可以通过多种方式实现,其中最常见的是使用Patroni和Repmgr。以下是使用Patroni和Repmgr搭建PostgreSQL集群的步骤:
安装必要的软件包 在所有节点上安装PostgreSQL、Patroni和相关的依赖包。
sudo apt-get update
sudo apt-get install -y postgresql-13 postgresql-13-patroni
配置PostgreSQL
在每个节点上编辑/etc/postgresql/13/main/postgresql.conf
文件,确保以下参数设置正确:
listen_addresses = '*' # 或者指定具体的IP地址
wal_level = replica
max_wal_senders = 10
wal_keep_segments = 64
hot_standby = on
编辑/etc/postgresql/13/main/pg_hba.conf
文件,添加允许其他节点连接的条目:
host replication replicator <其他节点的IP>/32 md5
host all all 0.0.0.0/0 md5
初始化Patroni配置
在主节点上创建Patroni配置文件/etc/patroni.yml
,示例如下:
scope: postgresql
name: master
namespace: /db/
restapi:
listen: 0.0.0.0:8008
connect_address: 192.168.1.101 # 主节点的IP地址
etcd:
host: 192.168.1.102 # etcd服务器的IP地址
port: 2379
use_ssl: false
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_wal_senders: 10
wal_keep_segments: 64
postgresql:
listen: 0.0.0.0:5432
connect_address: 192.168.1.101
data_dir: /var/lib/postgresql/13/main
pg_hba:
- host replication replicator 0.0.0.0/0 md5
- host all all 0.0.0.0/0 md5
authentication:
replication:
username: replicator
password: your_replicator_password
在从节点上创建类似的配置文件,修改scope
、name
和connect_address
字段。
启动Patroni 在主节点上启动Patroni:
sudo systemctl start patroni
sudo systemctl enable patroni
在从节点上启动Patroni:
sudo systemctl start patroni
sudo systemctl enable patroni
验证集群状态 使用Patroni提供的API检查集群状态:
curl http://192.168.1.101:8008/postgres
安装必要的软件包 在所有节点上安装PostgreSQL和Repmgr。
sudo apt-get update
sudo apt-get install -y postgresql-13 repmgr
配置PostgreSQL
在每个节点上编辑/etc/postgresql/13/main/postgresql.conf
文件,确保以下参数设置正确:
listen_addresses = '*' # 或者指定具体的IP地址
wal_level = replica
max_wal_senders = 10
wal_keep_segments = 64
hot_standby = on
编辑/etc/postgresql/13/main/pg_hba.conf
文件,添加允许其他节点连接的条目:
host replication replicator <其他节点的IP>/32 md5
host all all 0.0.0.0/0 md5
初始化Repmgr配置
在主节点上编辑/etc/repmgr/repmgr.conf
文件,示例如下:
node_id 1
node_name master
connect_address 192.168.1.101 # 主节点的IP地址
pg_bind_address 192.168.1.101
listen_address 192.168.1.101
auth_method md5
auth_key 'your_auth_key'
在从节点上编辑/etc/repmgr/repmgr.conf
文件,修改node_id
和node_name
字段。
启动Repmgr 在主节点上启动Repmgr:
sudo systemctl start repmgrd
sudo systemctl enable repmgrd
在从节点上启动Repmgr:
sudo systemctl start repmgrd
sudo systemctl enable repmgrd
初始化集群 在主节点上运行以下命令初始化集群:
sudo repmgr -f /etc/repmgr/repmgr.conf standby clone
验证集群状态 使用Repmgr提供的命令检查集群状态:
sudo repmgr cluster show
通过以上步骤,你可以在Linux上成功搭建一个PostgreSQL集群。选择Patroni还是Repmgr取决于你的具体需求和环境。Patroni提供了更高级的功能和更好的自动化管理,而Repmgr则是一个更轻量级的解决方案。