温馨提示×

centos如何集群postgresql

小樊
47
2026-09-03 08:37:55
栏目: 云计算

在 CentOS 上搭建 PostgreSQL 集群,需要先明确“集群”的具体目标,因为不同场景方案不同。下面我按常见用途给你分类说明,并给出主流方案 + 简要步骤


一、先明确:你要哪种“集群”?

需求 推荐方案
高可用(主挂了自动切换) Patroni + etcd + PostgreSQL
读写分离 / 热备 流复制(Streaming Replication)
多主写入 PostgreSQL 本身不支持(可用中间件)
分布式数据库 Citus / Postgres-XL
负载均衡 Pgpool-II / HAProxy

二、最常用:PostgreSQL 流复制(一主多备)

适用场景

  • 主库写入
  • 备库只读
  • 主库故障需手动或自动切换

环境示例

  • CentOS 7 / 8
  • PostgreSQL 14
  • 节点:
    • master:192.168.1.10
    • standby:192.168.1.11

1. 所有节点安装 PostgreSQL

sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum install -y postgresql14-server postgresql14

初始化(仅主节点):

/usr/pgsql-14/bin/postgresql-14-setup initdb
systemctl enable postgresql-14
systemctl start postgresql-14

2. 主库配置

编辑 postgresql.conf

listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = 1GB

编辑 pg_hba.conf

host replication repl 192.168.1.11/32 trust

创建复制用户:

CREATE ROLE repl LOGIN REPLICATION PASSWORD 'password';

重启主库:

systemctl restart postgresql-14

3. 备库配置

停止数据库:

systemctl stop postgresql-14

清空数据目录:

rm -rf /var/lib/pgsql/14/data/*

基础备份:

pg_basebackup -h 192.168.1.10 -U repl -D /var/lib/pgsql/14/data -P -R

启动备库:

systemctl start postgresql-14

✅ 此时已是 主从集群


三、高可用方案(推荐):Patroni + etcd

架构

etcd (3节点)
  ↓
Patroni (每个 PG 节点)
  ↓
PostgreSQL

优点

  • 自动故障转移
  • 无脑切换
  • 生产级

简要步骤

  1. 安装 etcd
  2. 安装 Patroni
  3. 编写 patroni.yml
  4. 启动 Patroni
  5. patronictl 管理集群

(这一步较复杂,如果你需要我可以给你完整配置文件 + 一步步命令


四、负载均衡 / 连接池

Pgpool-II

  • 连接池
  • 读写分离
  • 负载均衡

HAProxy + Patroni

  • 只连一个 VIP
  • 自动路由到主库

五、分布式方案(可选)

  • Citus:PostgreSQL 插件,适合大数据分析
  • Postgres-XL:真正分布式(较老)

六、我可以进一步帮你

你可以告诉我:

  1. CentOS 版本(7 / 8 / Stream)
  2. PostgreSQL 版本
  3. 是否要自动故障转移
  4. 几台机器

我可以直接给你: ✅ 可复制的配置文件
✅ 一键脚本思路
✅ 生产级架构图

你是学习用还是生产环境

0