PostgreSQLのリプリケーションをしてみるテスト

準備

postgresql94
AWS上にt1.smallでPostgresqlが動いているAmazon Linuxを2台構築。

Amazon Linux

$ cat /etc/os-release 
NAME="Amazon Linux AMI"
VERSION="2016.09"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2016.09"
PRETTY_NAME="Amazon Linux AMI 2016.09"
ANSI_COLOR="0;33"
CPE_NAME="cpe:/o:amazon:linux:2016.09:ga"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"

参考にしたウェブサイト

PostgreSQL レプリケーション構成を組んでみる - tom__bo’s Blog

PostgreSQL9.4でストリーミングレプリケーションする - マコーの日記

エラー1

-bash-4.2$ pg_basebackup -h 172.40.24.192 -p 5432 -D /var/lib/pgsql94/data --xlog --progress --verbose
pg_basebackup: could not connect to server: could not connect to server: Connection timed out
    Is the server running on host "172.40.24.192" and accepting
    TCP/IP connections on port 5432?

AWS の security group に自分自身のsgを許可(5432)

エラー2

-bash-4.2$ pg_basebackup -h 172.40.24.192 -p 5432 -D /var/lib/pgsql94/data --xlog --progress --verbose
pg_basebackup: could not connect to server: FATAL:  no pg_hba.conf entry for replication connection from host "172.40.135.122", user "postgres", SSL off

Postgresql doesn't accept replication connection - Database Administrators Stack Exchange

-bash-4.2$ diff pg_hba.conf pg_hba.conf.2017203 
85,86d84
< host    all             all             172.40.135.122/32        trust
< host    replication     postgres        172.40.135.122/32        trust

pg_basebackup が動いた。

-bash-4.2$ pg_basebackup -h 172.40.24.192 -p 5432 -D /var/lib/pgsql94/data --xlog --progress --verbose
transaction log start point: 0/E000028 on timeline 1
51646/51646 kB (100%), 1/1 tablespace                                         
transaction log end point: 0/E000128
pg_basebackup: base backup completed

メモ

Amazon Linux の場合、
recovery.conf.sample

/usr/share/pgsql94/recovery.conf.sample
にあった。

エラー3

INSERT文が止まる。
アプリも動かない(nginx 504 error: Gateway Timeout)

app1=> select application_name, client_addr, backend_start, state, sync_state from pg_stat_replication;
 application_name | client_addr | backend_start | state | sync_state 
------------------+-------------+---------------+-------+------------
 slave01          |             |               |       | 
(1 row)

参考にしたウェブサイトと違って client_addr や state などが空になっていた。
ただ、この状態はエラーの原因ではなかった。

http://dba.stackexchange.com/questions/50281/postgresql-replication-pg-stat-replication-is-showing-empty-columns

psql から INSERTして応答がなかったので、controll + c した時のメッセージ。

Cancel request sent
WARNING:  canceling wait for synchronous replication due to user request
DETAIL:  The transaction has already committed locally, but might not have been replicated to the standby.
INSERT 0 1

このエラーは、
master db の postgresql.conf に書く、synchronous_standby_names の値と
slave db の recovery.conf に書く、primary_conninfo の中の値が違っていると発生するっぽい。
レコード自体は作られていた。

postgresql.conf in master db.
synchronous_standby_names = 'slave01' # standby servers that provide sync rep

recovery.conf in slave db.
primary_conninfo = 'host=172.40.24.192 port=5432 application_name=slave01'