0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQLのstreaming replicationについて

0
Last updated at Posted at 2026-07-13

今さらですが、PostgreSQLのstreaming replicationについて
手順をまとめました。

サーバは3台用意し、1台をprimary, 2台をstanbyとします。
IPは以下の通りです

primray: 192.168.105.10
stanby-1: 192.168.105.20
stanby-2: 192.168.105.30

PostgreSQLのバージョンは 17.10 で検証しております。


[primaryの設定]

  • postgresql.conf を修正します
    listen_addresses = '*'
    wal_level = replica
    max_wal_senders = 5
    archive_mode = on
    archive_command = 'test ! -f /var/lib/pgsql/archive/%f && cp %p /var/lib/pgsql/archive/%f'
    hot_standby = on
    password_encryption = md5 ☆
    

    password_encryption は初期値が scram-sha-256 ですが、
    テストとして md5 にしています
    ここら辺は環境に応じて合わせてください

  • replication用のroleを作成します
    postgres=# CREATE ROLE {username} WITH LOGIN REPLICATION PASSWORD '{password}';
    
    usernameとpasswordはお好きな文字列をどうぞ
  • pg_hba.conf を修正します
    host    replication     {username}       192.168.105.0/24        md5
    
    usernameは作成したroleに合わせてください
    またmd5は必要に応じて修正してください
  • PostgreSQLを再起動します
    # systemctl restart postgresql-17
    

[stanbyの設定]
2台とも同じ設定です

  • PostgreSQLを停止します
    # systemctl stop postgresql-17
    
  • data directoryを削除します
    $ rm -rf $PGDATA/*
    

    この $PG_DATA 配下にはPostgreSQLの設定ファイルや、
    実際のデータが格納されています
    本番環境の場合はバックアップを取るなどしてください

  • primaryからデータを取得して配置します
    $ pg_basebackup -h 192.168.105.10 -U {username} -D $PGDATA -Fp -Xs -P -R
    
    usernameは作成したroleに合わせてください
    またpassword入力が求められますが、role作成時のものを入力してください
  • postgresql.conf を修正します
    primary_conninfo = 'host=192.168.105.10 port=5432 user={username} password={password} application_name={application_name}'
    
    username, passwordは作成したroleに合わせてください
    application_nameはstanby-1, stanby-2にしました
  • PostgreSQLを起動します
    # systemctl start postgresql-17
    

以上の設定が終了したら、
primaryでreplicationの確認をします

postgres=# SELECT application_name, client_addr, state, sync_state FROM pg_stat_replication;

うまく設定できていると以下のように結果が表示されます

 application_name |  client_addr   |   state   | sync_state
------------------+----------------+-----------+------------
 stanby-1         | 192.168.105.20 | streaming | async
 stanby-2         | 192.168.105.30 | streaming | async
(2 rows)

簡単ではありますが以上になります

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?