目標_
このレッスンの後、次のことを行います:
- Python と必要な依存関係をインストール
- pip 経由で Patroni をインストール_
- ファイルについて構造
patroni.yml - Patroni の systemd サービスを作成_
- Patroni を 3 つのノードにインストール
1。はじめに_
Patroni は Python アプリケーションであるため、Python ランタイムと依存関係が必要です。この記事では、
- Python 3 と pip をインストール
- Patroni パッケージをインストール
- Patroni 構成
- Patroni を管理する systemd サービスを作成します。デーモン
ターゲット アーキテクチャ:
┌──────────────────────────────────┐
│ etcd Cluster (3 nodes) │
│ ✅ RUNNING │
└──────────────────────────────────┘
│ │ │
┌────┴────┐ │ ┌─────┴─────┐
▼ ▼ ▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│Patroni 1│ │Patroni 2│ │Patroni 3│ ← Installing now
│ + PG │ │ + PG │ │ + PG │
└─────────┘ └─────────┘ └─────────┘
2。 Python の依存関係
2.1 をインストールします。 Ubuntu/Debian に Python をインストール
すべての 3 ノードで実行.
ステップ 1: Python 3 と pip をインストール_
# Update package list sudo apt updateCài Python 3, pip, và development tools
sudo apt install -y python3 python3-pip python3-dev python3-venv
Kiểm tra version
python3 --version
Output: Python 3.10.x (hoặc 3.11.x hoặc 3.12.x)
pip3 --version
Output: pip 22.x.x
Step 2: システムの依存関係_
# Cài các libraries cần thiết cho Patroni và PostgreSQL Python modules sudo apt install -y
libpq-dev
gcc
python3-psycopg2libpq-dev: PostgreSQL client library headers
gcc: Compiler cho building Python packages
python3-psycopg2: PostgreSQL adapter cho Python
2.2をインストールします。 CentOS/RHEL
# Python 3 thường đã có sẵn, nhưng cần pip và dev tools sudo dnf install -y python3 python3-pip python3-develSystem dependencies
sudo dnf install -y
postgresql18-devel
gcc
python3-psycopg2Kiểm tra
python3 --version pip3 --version
2.3 に Python をインストールします。 pip をアップグレードします (推奨)
# Upgrade pip to latest version sudo pip3 install --upgrade pipVerify
pip3 --version
3。 pip
3.1 経由で Patroni をインストールします。 Patroni をインストール_
すべての 3 ノードで実行._
# Cài Patroni với etcd support sudo pip3 install patroni[etcd]Hoặc specify version cụ thể
sudo pip3 install patroni[etcd]==3.2.0
Kiểm tra installation
patroni --version
Output: patroni 3.2.0
patronictl --version
Output: patronictl 3.2.0
ソリューションlike [etcd]:
- Patroni は多くの DCS バックエンド (etcd、consul、飼育員)
[etcd]追加追加python-etcdクライアントライブラリ- 複数インストール可能バックエンド:
patroni[etcd、領事、動物園飼育員]
3.2。インストールされたパッケージ
# Liệt kê các packages liên quan pip3 list | grep -E "(patroni|etcd|psycopg)"Output:
patroni 3.2.0
python-etcd 0.4.5
psycopg2 2.9.x
psycopg2-binary 2.9.x
3.3。 Patroni コマンド
# Check patroni binary which patroniOutput: /usr/local/bin/patroni
Check patronictl binary
which patronictl
Output: /usr/local/bin/patronictl
List patronictl commands
patronictl --help
Output:
Usage: patronictl [OPTIONS] COMMAND [ARGS]...
Commands: list Show cluster members switchover Perform planned switchover failover Perform manual failover reinit Reinitialize cluster member restart Restart cluster member reload Reload cluster member configuration pause Disable auto-failover resume Enable auto-failover edit-config Edit cluster configuration ...
4 を確認します。ファイル構造 patroni.yml
4.1。 patroni.yml
ファイル patroni.yml の概要は、Patroni の主な構成ファイルです。含まれるもの:
- スコープ: クラスター名
- 名前空間: キーのプレフィックスDCS_
- ノード情報: ノード名、REST API 構成
- DCS 接続_: etcdエンドポイント_
- ブートストラップ: クラスターの初期セットアップ_
- PostgreSQL: データベース構成_
- タグ: ノードのメタデータ
- ウォッチドッグ: オプションのハードウェアウォッチドッグ
4.2。基本構造
scope: postgres namespace: /service/ name: node1restapi: listen: 0.0.0.0:8008 connect_address: 10.0.1.11:8008
etcd: hosts: 10.0.1.11:2379,10.0.1.12:2379,10.0.1.13:2379
bootstrap: 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: 10 max_replication_slots: 10
initdb: - encoding: UTF8 - data-checksums
pg_hba: - host replication replicator 10.0.1.0/24 scram-sha-256 - host all all 0.0.0.0/0 scram-sha-256
postgresql: listen: 0.0.0.0:5432 connect_address: 10.0.1.11:5432 data_dir: /var/lib/postgresql/18/data bin_dir: /usr/lib/postgresql/18/bin authentication: replication: username: replicator password: replicator_password superuser: username: postgres password: postgres_password
tags: nofailover: false noloadbalance: false clonefrom: false nosync: false
4.3.主要セクションの説明_
セクション: グローバル
scope: postgres # Cluster name (unique identifier)
namespace: /service/ # DCS key prefix
name: node1 # Unique node name trong cluster
セクション: REST API_
restapi: listen: 0.0.0.0:8008 # Listen trên tất cả interfaces connect_address: 10.0.1.11:8008 # Address để nodes khác connectauthentication: # Optional: Basic auth
username: admin
password: secret
REST APIエンドポイント:
GET /: クラスター情報GET /health: ヘルスチェック (200 =健全)GET /primary_: ノードがプライマリかどうかを確認_GET /replica: ノードがレプリカかどうかを確認POST /restart_: PostgreSQL を再起動_POST /reload: 設定をリロード
セクション: etcd (DCS)
etcd: hosts: 10.0.1.11:2379,10.0.1.12:2379,10.0.1.13:2379 # etcd endpointsprotocol: http # http hoặc https
username: user # Optional: etcd authentication
password: pass
セクション: ブートストラップ_
bootstrap: dcs: ttl: 30 # Leader lock TTL (seconds) loop_wait: 10 # Check interval (seconds) retry_timeout: 10 # DCS operation timeout maximum_lag_on_failover: 1048576 # Max lag (bytes) để eligible for failover postgresql: use_pg_rewind: true # Enable pg_rewind for fast recovery parameters: # PostgreSQL parameters wal_level: replica hot_standby: "on" wal_keep_size: "1GB" max_wal_senders: 10 max_replication_slots: 10 wal_log_hints: "on" # Required for pg_rewindinitdb: # pg_initdb options - encoding: UTF8 - data-checksums # Enable page checksums - locale: en_US.UTF-8
pg_hba: # pg_hba.conf entries - host replication replicator 10.0.1.0/24 scram-sha-256 - host all all 0.0.0.0/0 scram-sha-256
users: # Create users during bootstrap admin: password: admin_password options: - createrole - createdb
注: ブートストラップ セクションは、クラスターを初めて初期化する場合にのみ適用されます。
セクション: PostgreSQL
postgresql: listen: 0.0.0.0:5432 # PostgreSQL listen address connect_address: 10.0.1.11:5432 # Address để connect từ bên ngoài data_dir: /var/lib/postgresql/18/data # Data directory bin_dir: /usr/lib/postgresql/18/bin # PostgreSQL binaries pgpass: /tmp/pgpass # Optional: pgpass fileauthentication: replication: username: replicator password: replicator_password superuser: username: postgres password: postgres_password rewind: # Optional: dedicated user for pg_rewind username: rewind_user password: rewind_password
parameters: # PostgreSQL runtime parameters max_connections: 100 shared_buffers: 2GB effective_cache_size: 6GB maintenance_work_mem: 512MB checkpoint_completion_target: 0.9 wal_buffers: 16MB default_statistics_target: 100 random_page_cost: 1.1 effective_io_concurrency: 200 work_mem: 16MB min_wal_size: 1GB max_wal_size: 2GB
pg_hba: # Additional pg_hba.conf entries - host all all 10.0.2.0/24 scram-sha-256
callbacks: # Optional: callback scripts on_start: /etc/patroni/scripts/on_start.sh on_stop: /etc/patroni/scripts/on_stop.sh on_role_change: /etc/patroni/scripts/on_role_change.sh
セクション: タグ
tags: nofailover: false # false = có thể become primary noloadbalance: false # false = có thể nhận read traffic clonefrom: false # false = có thể clone từ node này nosync: false # false = có thể become synchronous standbyCustom tags
datacenter: dc1 environment: production
セクション: ウォッチドッグ (オプション)
watchdog:
mode: required # required, automatic, hoặc off
device: /dev/watchdog # Hardware watchdog device
safety_margin: 5 # Seconds before watchdog triggers
5。 Patroni 設定ファイル
5.1 を作成します。構成ディレクトリ
オン すべて 3 ノード:
# Tạo directory cho Patroni config sudo mkdir -p /etc/patroniTạo directory cho callback scripts (optional)
sudo mkdir -p /etc/patroni/scripts
Set ownership
sudo chown -R postgres:postgres /etc/patroni
5.2 を作成します。ノード 1 - /etc/patroni/patroni.yml
scope: postgres namespace: /service/ name: node1restapi: listen: 0.0.0.0:8008 connect_address: 10.0.1.11:8008
etcd: hosts: 10.0.1.11:2379,10.0.1.12:2379,10.0.1.13:2379
bootstrap: 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" wal_keep_size: "1GB" max_wal_senders: 10 max_replication_slots: 10 wal_log_hints: "on"
initdb: - encoding: UTF8 - data-checksums
pg_hba: - host replication replicator 10.0.1.11/32 scram-sha-256 - host replication replicator 10.0.1.12/32 scram-sha-256 - host replication replicator 10.0.1.13/32 scram-sha-256 - host all all 10.0.1.0/24 scram-sha-256 - host all all 0.0.0.0/0 md5
users: admin: password: admin123 options: - createrole - createdb
postgresql: listen: 0.0.0.0:5432 connect_address: 10.0.1.11:5432 data_dir: /var/lib/postgresql/18/data bin_dir: /usr/lib/postgresql/18/bin authentication: replication: username: replicator password: replicator_password superuser: username: postgres password: postgres_password parameters: max_connections: 100 shared_buffers: 2GB effective_cache_size: 6GB maintenance_work_mem: 512MB checkpoint_completion_target: 0.9
tags: nofailover: false noloadbalance: false clonefrom: false nosync: false
5.3。ノード 2 - /etc/patroni/patroni.yml
scope: postgres namespace: /service/ name: node2restapi: listen: 0.0.0.0:8008 connect_address: 10.0.1.12:8008
etcd: hosts: 10.0.1.11:2379,10.0.1.12:2379,10.0.1.13:2379
bootstrap: 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" wal_keep_size: "1GB" max_wal_senders: 10 max_replication_slots: 10 wal_log_hints: "on"
initdb: - encoding: UTF8 - data-checksums
pg_hba: - host replication replicator 10.0.1.11/32 scram-sha-256 - host replication replicator 10.0.1.12/32 scram-sha-256 - host replication replicator 10.0.1.13/32 scram-sha-256 - host all all 10.0.1.0/24 scram-sha-256 - host all all 0.0.0.0/0 md5
users: admin: password: admin123 options: - createrole - createdb
postgresql: listen: 0.0.0.0:5432 connect_address: 10.0.1.12:5432 data_dir: /var/lib/postgresql/18/data bin_dir: /usr/lib/postgresql/18/bin authentication: replication: username: replicator password: replicator_password superuser: username: postgres password: postgres_password parameters: max_connections: 100 shared_buffers: 2GB effective_cache_size: 6GB maintenance_work_mem: 512MB checkpoint_completion_target: 0.9
tags: nofailover: false noloadbalance: false clonefrom: false nosync: false
5.4。ノード 3 - /etc/patroni/patroni.yml
scope: postgres namespace: /service/ name: node3restapi: listen: 0.0.0.0:8008 connect_address: 10.0.1.13:8008
etcd: hosts: 10.0.1.11:2379,10.0.1.12:2379,10.0.1.13:2379
bootstrap: 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" wal_keep_size: "1GB" max_wal_senders: 10 max_replication_slots: 10 wal_log_hints: "on"
initdb: - encoding: UTF8 - data-checksums
pg_hba: - host replication replicator 10.0.1.11/32 scram-sha-256 - host replication replicator 10.0.1.12/32 scram-sha-256 - host replication replicator 10.0.1.13/32 scram-sha-256 - host all all 10.0.1.0/24 scram-sha-256 - host all all 0.0.0.0/0 md5
users: admin: password: admin123 options: - createrole - createdb
postgresql: listen: 0.0.0.0:5432 connect_address: 10.0.1.13:5432 data_dir: /var/lib/postgresql/18/data bin_dir: /usr/lib/postgresql/18/bin authentication: replication: username: replicator password: replicator_password superuser: username: postgres password: postgres_password parameters: max_connections: 100 shared_buffers: 2GB effective_cache_size: 6GB maintenance_work_mem: 512MB checkpoint_completion_target: 0.9
tags: nofailover: false noloadbalance: false clonefrom: false nosync: false
5.5。権限を設定
オン すべての 3 ノード:
# Set ownership sudo chown postgres:postgres /etc/patroni/patroni.ymlSecure permissions (file chứa passwords)
sudo chmod 600 /etc/patroni/patroni.yml
Verify
ls -l /etc/patroni/patroni.yml
Output: -rw------- 1 postgres postgres ... patroni.yml
6。 Patroni
6.1 の systemd サービスを作成します。 systemd ユニット ファイルを作成
ファイルを作成 /etc/systemd/system/patroni.service on ALL 3ノード_:
[Unit] Description=Patroni PostgreSQL HA manager Documentation=https://patroni.readthedocs.io/ After=syslog.target network.target etcd.service[Service] Type=simple User=postgres Group=postgres
Start Patroni
ExecStart=/usr/local/bin/patroni /etc/patroni/patroni.yml
Reload configuration
ExecReload=/bin/kill -HUP $MAINPID
Restart behavior
Restart=on-failure RestartSec=5
Limits
LimitNOFILE=65536 LimitNPROC=65536
Logging
StandardOutput=journal StandardError=journal
Working directory
WorkingDirectory=/var/lib/postgresql
Environment
Environment=PATH=/usr/lib/postgresql/18/bin:/usr/local/bin:/usr/bin:/bin
[Install] WantedBy=multi-user.target
6.2。 systemd ユニット ファイルの説明
| _ディレクティブ | 解決策like_ |
|---|---|
After=etcd.service_ | etcd の後に開始準備完了_ |
Type=simple_ | プロセス実行中foreground_ |
User=postgres_ | _ユーザー postgres で実行 |
ExecStart | 開始コマンドPatroni_ |
ExecReload_ | HUP 信号を送信してリロードするconfig_ |
Restart=on-failure_ | 自動再起動の場合失敗_ |
_RestartSec=5 | 5 秒前まで待つ再起動_ |
_LimitNOFILE=65536_ | 最大オープンファイル_ |
_StandardOutput=journal_ | systemd ジャーナルにログイン |
6.3.サービス
オン ALL 3 ノード:
# Reload systemd sudo systemctl daemon-reloadEnable Patroni service (auto-start on boot)
sudo systemctl enable patroni
Verify service file
systemctl cat patroni
Check status (should be inactive/dead - not started yet)
systemctl status patroni
7 を有効にして確認します。インストールを確認
7.1。 Patroni のインストール
オン すべて 3 ノード:
# Check Patroni version patroni --versionCheck patronictl
patronictl --help
Verify config file
sudo -u postgres cat /etc/patroni/patroni.yml
Validate YAML syntax
python3 -c "import yaml; yaml.safe_load(open('/etc/patroni/patroni.yml'))"
No output = valid YAML
7.2 を確認します。 etcd 接続を確認します
# Test etcd từ mỗi node etcdctl endpoint health --clusterShould see all 3 etcd nodes healthy
7.3。飛行前チェックリスト
Patroni を開始する前に、
# ✅ PostgreSQL installed nhưng NOT running systemctl status postgresqlShould be: inactive (dead)
✅ etcd cluster healthy
etcdctl endpoint health --cluster
✅ Patroni config file exists và có permissions đúng
ls -l /etc/patroni/patroni.yml
✅ Data directory có ownership đúng
ls -ld /var/lib/postgresql/18/data
Owner: postgres:postgres
✅ systemd service enabled
systemctl is-enabled patroni
Output: enabled
✅ Firewall rules (nếu có firewall)
sudo ufw status | grep -E "(5432|8008)"
Hoặc
sudo firewall-cmd --list-ports | grep -E "(5432|8008)"
8 を確認してください。トラブルシューティング
8.1。問題: pip インストールが失敗
# Error: "No module named 'setuptools'"Solution:
sudo apt install python3-setuptools
Or upgrade pip
sudo pip3 install --upgrade pip setuptools
8.2。問題: PostgreSQL バイナリ_
# Error: "could not find postgres binary"Solution: Check bin_dir in patroni.yml
Find PostgreSQL bin directory
which postgres
Output: /usr/lib/postgresql/18/bin/postgres
Update patroni.yml
postgresql: bin_dir: /usr/lib/postgresql/18/bin
8.3 が見つかりません。問題: データ ディレクトリ_
# Error: "FATAL: data directory ... has wrong ownership"Solution:
sudo chown -R postgres:postgres /var/lib/postgresql/18/data sudo chmod 700 /var/lib/postgresql/18/data
8.4 で権限が拒否されました。問題: YAML 構文エラー
# Validate YAML python3 -c "import yaml; yaml.safe_load(open('/etc/patroni/patroni.yml'))"Common issues:
- Mixed tabs and spaces (use spaces only)
- Incorrect indentation
- Missing quotes around special characters
- Duplicate keys
9。概要
重要なポイント
✅ Patroni: Python アプリケーション、インストールpip
✅ 依存関係: Python 3、pip、psycopg2、 python-etcd
✅ 構成: patroni.yml すべてが含まれています設定
✅ systemd サービス: Patroni デーモン管理
✅ セキュリティ: 構成ファイルには権限 600 があります。 (パスワードを含む)
ラボ後のチェックリスト
- Python 3 と pip が 3 つのノードすべてにインストールされている
- Patroni 3.2.0 以降が 3 つのノードすべてにインストールされているノード
- ファイル
/etc/patroni/patroni.yml独自の構成 - systemd を使用して各ノードにすでに作成されています。サービス
patroni.service作成および有効化 - 構成ファイルに対する権限が true (600、所有者 postgres)
- etcd クラスターは実行されており、正常です
現在のアーキテクチャ_
✅ 3 VMs prepared (Bài 4) ✅ PostgreSQL 18 installed (Bài 5) ✅ etcd cluster running (Bài 6) ✅ Patroni installed and configured (Bài 7)
Next: Bootstrap cluster lần đầu
レッスン 8 の準備_
レッスン 8 はさらに深くなります。詳細な Patroni に移動します。設定:
patroni.yml- ブートストラップ設定オプション
- PostgreSQL パラメータチューニング_
- 認証セットアップ_
- タグと制約_
レッスン 9: ブートストラップ クラスター
Patroni のインストールと構成が完了したら、レッスン 9 で次のことを行います。ガイド:
- Patroni の初めての起動
- 動的自動ブートストラッププロセス
- クラスターステータスの確認
- トラブルシューティング