在Ubuntu下搭建PostgreSQL集群,通常指的是设置一个高可用的PostgreSQL集群,例如使用Patroni和Keepalived来实现。以下是一个基本的步骤指南:
在每个节点上安装PostgreSQL:
sudo apt update
sudo apt install postgresql postgresql-contrib
编辑/etc/postgresql/<version>/main/postgresql.conf文件,确保以下参数设置正确:
listen_addresses = '*' # 或者指定具体的IP地址
wal_level = replica
max_wal_senders = 10
wal_keep_segments = 64
hot_standby = on
编辑/etc/postgresql/<version>/main/pg_hba.conf文件,添加以下行以允许从其他节点进行连接:
host replication replicator <其他节点的IP>/32 md5
重启PostgreSQL服务:
sudo systemctl restart postgresql
在主节点上创建一个复制用户:
CREATE USER replicator WITH REPLICATION PASSWORD 'your_password' LOGIN;
在主节点上创建一个用于复制的数据库:
CREATE DATABASE replication_db;
在从节点上配置recovery.conf(PostgreSQL 9.6及以下版本)或postgresql.auto.conf(PostgreSQL 10及以上版本):
standby_mode = 'on'
primary_conninfo = 'host=<主节点IP> dbname=replication_db user=replicator password=your_password'
trigger_file = '/tmp/postgresql.trigger.5432'
在所有节点上安装Patroni:
sudo apt install python3-pip
sudo pip3 install patroni
创建Patroni配置文件/etc/patroni.yml,示例如下:
scope: postgresql
name: pg1
namespace: /db/
restapi:
listen: 0.0.0.0:8008
connect_address: <当前节点IP>
etcd:
host: <etcd节点IP>: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_wal_senders: 10
wal_keep_segments: 64
replication:
slot_name: pg1_slot
listen: 0.0.0.0:5432
connect_address: <当前节点IP>
authentication:
username: replicator
password: your_password
nodes:
- name: pg1
host: <当前节点IP>
port: 5432
data_dir: /var/lib/postgresql/12/main
pg_hba:
- host replication replicator <其他节点IP>/32 md5
- host all all 0.0.0.0/0 md5
在所有节点上启动Patroni:
sudo patroni /etc/patroni.yml
如果你希望使用Keepalived来实现VIP(虚拟IP),可以按照以下步骤进行配置:
安装Keepalived:
sudo apt install keepalived
创建Keepalived配置文件/etc/keepalived/keepalived.conf,示例如下:
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass your_password
}
virtual_ipaddress {
<VIP地址>
}
}
启动Keepalived:
sudo systemctl start keepalived
确保所有节点都正常运行,并且可以通过VIP访问PostgreSQL集群。
通过以上步骤,你应该能够在Ubuntu下成功搭建一个基本的PostgreSQL集群。根据实际需求,你可能需要进一步调整配置和优化性能。