提交工单

香港服务器PostgreSQL主从流复制 + Patroni自动故障切换高可用方案完整实战

文档更新于

数据库是业务的核心,单点 PostgreSQL 的任何故障都意味着业务中断。PostgreSQL 流复制让从节点实时同步主节点的 WAL 日志,数据延迟通常在毫秒级。Patroni 在流复制基础上实现自动故障切换——主节点宕机时,Patroni 在从节点中自动选举新主节点,整个切换过程约 10~30 秒,应用层通过 HAProxy 透明感知,无需手动介入。


一、架构设计

<code">
香港服务器集群(3节点):

DB-1(10.0.0.1):PostgreSQL + Patroni + etcd
DB-2(10.0.0.2):PostgreSQL + Patroni + etcd
DB-3(10.0.0.3):PostgreSQL + Patroni + etcd

HAProxy(可与应用服务器同机):
  - 5432 → 当前主节点(读写)
  - 5433 → 所有从节点(只读,轮询)

etcd(分布式配置存储):
  - 记录当前 Leader(主节点)
  - 提供 Patroni 的分布式锁(防脑裂)

二、安装 PostgreSQL 和 Patroni(所有节点)

<code"># 安装 PostgreSQL 16
apt install -y postgresql-16 postgresql-client-16

# 安装 Patroni 和 etcd 客户端
apt install -y python3-pip python3-dev libpq-dev

pip3 install patroni[etcd] psycopg2-binary

# 安装 etcd
apt install -y etcd

# 停止 PostgreSQL(由 Patroni 接管)
systemctl stop postgresql
systemctl disable postgresql

三、配置 etcd(三节点集群)

<code"># /etc/etcd/etcd.conf(以 DB-1 为例)
ETCD_NAME="db-1"
ETCD_DATA_DIR="/var/lib/etcd"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_INITIAL_CLUSTER_TOKEN="pg-ha-cluster"
ETCD_INITIAL_CLUSTER="db-1=http://10.0.0.1:2380,db-2=http://10.0.0.2:2380,db-3=http://10.0.0.3:2380"

ETCD_LISTEN_CLIENT_URLS="http://0.0.0.0:2379"
ETCD_ADVERTISE_CLIENT_URLS="http://10.0.0.1:2379"

ETCD_LISTEN_PEER_URLS="http://0.0.0.0:2380"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://10.0.0.1:2380"

# DB-2 修改:ETCD_NAME=db-2,IP 改为 10.0.0.2
# DB-3 修改:ETCD_NAME=db-3,IP 改为 10.0.0.3

systemctl enable --now etcd

# 验证 etcd 集群
etcdctl member list

四、Patroni 配置(每台服务器)

<code"># /etc/patroni/patroni.yml(以 DB-1 为例)
scope: pg-ha-cluster      # 集群名称
namespace: /db/
name: db-1                # 本节点名称

restapi:
  listen: 10.0.0.1:8008
  connect_address: 10.0.0.1:8008

etcd3:
  hosts: 10.0.0.1:2379,10.0.0.2:2379,10.0.0.3:2379

bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576   # 从节点最大落后量(字节)

  initdb:
    - encoding: UTF8
    - data-checksums

  pg_hba:
    - host replication replicator 10.0.0.0/24 md5
    - host all all 0.0.0.0/0 md5

  users:
    admin:
      password: AdminPass2026
      options:
        - createrole
        - createdb

postgresql:
  listen: 0.0.0.0:5432
  connect_address: 10.0.0.1:5432     # 本机IP

  data_dir: /var/lib/postgresql/16/main
  bin_dir: /usr/lib/postgresql/16/bin
  config_dir: /etc/postgresql/16/main

  authentication:
    replication:
      username: replicator
      password: ReplPass2026
    superuser:
      username: postgres
      password: PostgresPass2026
    rewind:
      username: rewind_user
      password: RewindPass2026

  parameters:
    max_connections: 200
    shared_buffers: 2GB
    effective_cache_size: 6GB
    wal_level: replica
    hot_standby: "on"
    max_wal_senders: 10
    max_replication_slots: 10
    hot_standby_feedback: "on"

tags:
  nofailover: false
  noloadbalance: false
  clonedfrom: false
  nosync: false
<code"># 创建 Patroni systemd 服务
cat > /etc/systemd/system/patroni.service << 'EOF'
[Unit]
Description=Patroni PostgreSQL HA Cluster
After=etcd.service

[Service]
Type=simple
User=postgres
Group=postgres
ExecStart=/usr/local/bin/patroni /etc/patroni/patroni.yml
Restart=on-failure
TimeoutSec=30

[Install]
WantedBy=multi-user.target
EOF

chown postgres:postgres /etc/patroni/patroni.yml
systemctl enable --now patroni

# 查看集群状态
patronictl -c /etc/patroni/patroni.yml list

五、HAProxy 负载均衡(读写分离)

<code"># /etc/haproxy/haproxy.cfg(在应用服务器上安装 HAProxy)
global
    log /dev/log local0
    maxconn 10000

defaults
    log global
    mode tcp
    retries 2
    timeout connect 5s
    timeout client 30m
    timeout server 30m

# 主节点端口(读写)
frontend pg_write
    bind *:5432
    default_backend pg_master

backend pg_master
    option httpchk GET /master    # Patroni REST API 检查是否是主节点
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
    server db-1 10.0.0.1:5432 check port 8008
    server db-2 10.0.0.2:5432 check port 8008
    server db-3 10.0.0.3:5432 check port 8008

# 从节点端口(只读)
frontend pg_read
    bind *:5433
    default_backend pg_replicas

backend pg_replicas
    option httpchk GET /replica   # 检查是否是从节点
    http-check expect status 200
    balance roundrobin
    default-server inter 3s fall 3 rise 2
    server db-1 10.0.0.1:5432 check port 8008
    server db-2 10.0.0.2:5432 check port 8008
    server db-3 10.0.0.3:5432 check port 8008

# HAProxy 状态页
frontend stats
    bind *:7000
    stats enable
    stats uri /stats
    stats auth admin:haproxy_pass

systemctl restart haproxy

六、故障切换测试

<code"># 查看当前集群状态
patronictl -c /etc/patroni/patroni.yml list
# 输出示例:
# + Cluster: pg-ha-cluster (7234567890) ---------+----+-----------+
# | Member | Host       | Role    | State   | TL | Lag in MB |
# +--------+------------+---------+---------+----+-----------+
# | db-1   | 10.0.0.1:5 | Leader  | running |  1 |           |
# | db-2   | 10.0.0.2:5 | Replica | running |  1 |         0 |
# | db-3   | 10.0.0.3:5 | Replica | running |  1 |         0 |

# 手动触发故障切换(测试)
patronictl -c /etc/patroni/patroni.yml failover pg-ha-cluster --master db-1

# 模拟主节点宕机
systemctl stop patroni   # 在 DB-1 上执行

# 观察新主节点选举(约10-30秒)
watch patronictl -c /etc/patroni/patroni.yml list

# 应用连接字符串(连接 HAProxy,无需关心哪台是主节点)
# DATABASE_URL=postgresql://admin:AdminPass2026@haproxy_host:5432/mydb

七、复制延迟监控

<code">-- 在主节点查看复制状态
SELECT
    client_addr,
    state,
    sent_lsn,
    write_lsn,
    flush_lsn,
    replay_lsn,
    pg_size_pretty(pg_wal_lsn_diff(sent_lsn, replay_lsn)) AS lag_size
FROM pg_stat_replication;

-- 设置告警:复制延迟超过 10MB 时告警
-- 在 Grafana 中查询 Patroni metrics(通过 Prometheus)
# patroni_postgres_streaming_lag_bytes > 10485760

八、总结

PostgreSQL + Patroni + HAProxy + etcd 构成了企业级数据库高可用方案的黄金组合,在香港多台服务器上部署后,主节点故障到自动切换完成约 10~30 秒,对大多数业务来说这个窗口期可以接受(结合应用层重试逻辑),实现了数据库层的真正高可用。与 MySQL MGR 相比,PostgreSQL 方案的数据一致性保证更强,适合对数据准确性要求严格的金融和电商场景。

需要服务器?

香港 / 美国 / 日本服务器与 VPS,工程师 7×24 在线,工单平均 10 分钟内响应。