温馨提示×

centos怎样集群postgresql

小樊
37
2026-09-15 14:23:20
栏目: 云计算

在 CentOS 上搭建 PostgreSQL 集群,常见方案有几种,取决于你的目标:高可用(HA)、读写分离、还是分布式扩展。下面我按“最常用、最稳妥”的方式给你讲,并给出可操作的步骤。


一、先明确集群类型

类型 说明 常用方案
主从复制(热备) 一主多从,读写分离 Streaming Replication
高可用(自动故障切换) 主挂了自动切 Patroni + etcd + HAProxy
分布式数据库 水平扩展 Citus / PostgreSQL-XL

✅ 90% 的 CentOS PostgreSQL 集群 = 流复制 + Patroni


二、基础环境准备(所有节点)

假设:

  • 节点1:192.168.1.10(主)
  • 节点2:192.168.1.11(从)
  • CentOS 7/8
  • PostgreSQL 14(示例)

1. 关闭防火墙或放行端口

systemctl stop firewalld
systemctl disable firewalld
# 或
firewall-cmd --add-port=5432/tcp --permanent
firewall-cmd --reload

2. 配置主机名解析

vi /etc/hosts
192.168.1.10 pg1
192.168.1.11 pg2

3. 安装 PostgreSQL

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

三、方式一:PostgreSQL 流复制(最基础)

1. 主节点配置

/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;

2. 从节点

pg_basebackup -h 192.168.1.10 -U repluser -D /var/lib/pgsql/14/data -P -R
systemctl start postgresql-14

✅ 此时已是 主从集群


四、方式二:Patroni + etcd(推荐高可用)

1. 安装 etcd(所有节点)

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"

2. 安装 Patroni

pip3 install patroni[etcd]

3. patroni.yml 示例

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

4. 启动

patroni /etc/patroni.yml

✅ 自动选主 + 故障切换


五、前端访问(可选)

yum install haproxy

用 HAProxy 做 5432 端口统一入口


六、常用集群命令

patronictl list
patronictl switchover
pg_ls_replication_slots()

七、总结建议

  • ✅ 学习/测试:流复制
  • ✅ 生产环境:Patroni + etcd
  • ✅ 超大规模:Citus

如果你愿意,我可以:

  • 给你 完整一键脚本
  • 按 CentOS 7 / 8 细分
  • 画一张 架构图

你现在是测试还是生产环境?

0 踩