在当今高并发、高可用的应用场景中,单点数据库已无法满足业务需求。本文将带你从零开始,在 Debian系统 上部署一套高可用的 PostgreSQL数据库集群,即使你是 Linux 小白,也能轻松上手!本教程涵盖环境准备、主从配置、故障切换和基本测试,助你掌握 Debian数据库集群 的核心技能。
你需要准备以下资源:
假设三台服务器 IP 如下:
我们使用 Patroni 作为高可用管理工具,配合 etcd 实现自动故障转移。
在所有节点执行以下命令:
# 更新系统sudo apt update && sudo apt upgrade -y# 安装 PostgreSQL 14sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -sudo apt updatesudo apt install postgresql-14 postgresql-client-14 -y# 安装 Patroni 和 etcd(仅用于协调)sudo apt install python3-pip etcd -ypip3 install patroni[etcd]
为简化,我们在主节点运行单节点 etcd(生产环境建议 3 节点):
# 编辑 etcd 配置文件sudo nano /etc/default/etcd# 添加以下内容ETCD_LISTEN_PEER_URLS="http://192.168.1.10:2380"ETCD_LISTEN_CLIENT_URLS="http://localhost:2379,http://192.168.1.10:2379"ETCD_INITIAL_ADVERTISE_PEER_URLS="http://192.168.1.10:2380"ETCD_ADVERTISE_CLIENT_URLS="http://192.168.1.10:2379"ETCD_INITIAL_CLUSTER="default=http://192.168.1.10:2380"ETCD_INITIAL_CLUSTER_STATE="new"
启动 etcd:
sudo systemctl enable etcdsudo systemctl start etcd
在所有数据库节点创建 Patroni 配置文件 /etc/patroni.yml:
scope: mydb_clusternamespace: /db/name: pg_node_1 # 每个节点名字不同,如 pg_node_2、pg_node_3restapi: listen: 192.168.1.10:8008 # 对应本机IP connect_address: 192.168.1.10:8008etcd: host: 192.168.1.10:2379bootstrap: dcs: ttl: 30 loop_wait: 10 retry_timeout: 10 maximum_lag_on_failover: 1048576 postgresql: use_pg_rewind: true parameters: wal_level: replica hot_standby: "on" max_wal_senders: 8 wal_keep_segments: 8 max_replication_slots: 8postgresql: listen: 192.168.1.10:5432 connect_address: 192.168.1.10:5432 data_dir: /var/lib/postgresql/14/main bin_dir: /usr/lib/postgresql/14/bin authentication: replication: username: replicator password: your_replicator_password superuser: username: postgres password: your_postgres_password parameters: unix_socket_directories: '/var/run/postgresql'
注意:每个节点需修改 name、listen 和 connect_address 为本机 IP。
在主节点(192.168.1.10)首次启动 Patroni,它会自动初始化数据库:
sudo patroni /etc/patroni.yml
看到日志中出现 initialized a new cluster 表示成功。
然后在其他两个从节点也执行相同命令,Patroni 会自动加入集群并同步数据。
查看集群状态:
curl http://192.168.1.10:8008/cluster
你应该看到类似输出:
{ "members": [ {"name":"pg_node_1","role":"leader","state":"running","api_url":"http://192.168.1.10:8008"}, {"name":"pg_node_2","role":"replica","state":"running","api_url":"http://192.168.1.11:8008"}, {"name":"pg_node_3","role":"replica","state":"running","api_url":"http://192.168.1.12:8008"} ]} 现在你可以模拟主节点宕机(kill Patroni 进程),观察是否自动切换 leader。这就是 高可用数据库部署 的核心价值!
通过本教程,你已经成功在 Debian系统 上搭建了一套基于 Patroni + etcd 的 PostgreSQL集群。这套方案具备自动故障转移、数据同步和健康检查能力,非常适合中小型企业构建稳定可靠的数据库服务。
记住关键词:Debian数据库集群、高可用数据库部署、PostgreSQL集群教程、Debian系统数据库 —— 这些是你后续深入学习和运维的关键。
祝你部署顺利!如有问题,欢迎查阅官方文档或社区论坛。
本文由主机测评网于2025-12-19发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/20251210152.html