PostgreSQLでロジカルレプリケーションを最小限に構成

流れ

  1. 下記ファイルを利用してDockerコンテナを2つ作成(PrimaryとSecondary)。
    (pg_hba.confは特別触っていない。Dockerだからなのか、デフォルトでできる状態だった)
  2. Primary側でテーブル作成、データ挿入、パブリケーション作成。
  3. Secondary側でテーブル作成、サブスクリプション作成。
  4. 同期できてることを確認。

準備するファイル

.envファイル

COMPOSE_PROJECT_NAME=postgresql_replication

docker-compose.yml

version: "3"
services:
  primary:
    build: ./Primary
    container_name: PrimaryPostgreSQL
    ports:
      - 5432:5432
    volumes:
      - /プロジェクトのディレクトリ/Primary/postgresql.conf:/etc/postgresql/postgresql.conf
    command: '-c config_file=/etc/postgresql/postgresql.conf'

  secondary:
    build: ./Secondary
    container_name: SecondaryPostgreSQL
    ports:
      - 5433:5433
    volumes:
      - /プロジェクトのディレクトリ/Secondary/postgresql.conf:/etc/postgresql/postgresql.conf
    command: '-c config_file=/etc/postgresql/postgresql.conf'

PrimaryとSecondaryのDockerfile

FROM postgres:14.9
LABEL authors="shinke1987"

# アップデート。
RUN apt-get update
RUN apt-get -y install less

# タイムゾーンの設定。
RUN cp /usr/share/zoneinfo/Asia/Tokyo /etc/localtime



# スーパーユーザのユーザ名を設定。
ENV POSTGRES_USER shinke1987

# スーパーユーザのパスワードを設定。
ENV POSTGRES_PASSWORD password

# デフォルトのDBの名前を設定。
ENV POSTGRES_DB TestDB

# initdb実行時のオプションを設定。
ENV POSTGRES_INITDB_ARGS='-E UTF8 --no-locale'

Primaryのpostgresql.conf

この3行だけでとりあえず動く。

listen_addresses = '*'
port = 5432
wal_level = logical

Secondaryのpostgresql.conf

この2行だけでとりあえず動く。

listen_addresses = '*'
port = 5433

SQL等

Primary側で実行

-- 【Primary】テーブル作成。
CREATE TABLE table1 (
    id integer,
    data varchar(10)
);

-- 【Primary】データ挿入。
INSERT INTO table1
VALUES (1, 'data1')
, (2, 'data2');

-- 【Primary】パブリケーション作成。
CREATE PUBLICATION test_publication FOR TABLE table1;

-- 【Primary】パブリケーションが作成できていることを確認。
SELECT * FROM pg_publication WHERE pubname = 'test_publication';

Secondary側で実行

※ 一応SecondaryのコンテナからpsqlでPrimaryコンテナのPostgreSQLに接続できることは確認した。

-- 【Secondary】データを受信する側のテーブルを作成。
CREATE TABLE table1 (
    id integer,
    data varchar(10)
);

-- 【Secondary】サブスクリプション作成。
CREATE SUBSCRIPTION test_subscription
    CONNECTION 'host=PrimaryPostgreSQL port=5432 dbname=TestDB user=shinke1987 password=password'
    PUBLICATION test_publication;

-- 【Secondary】サブスクリプションが作成できていることを確認。
SELECT * FROM pg_subscription WHERE subname = 'test_subscription';

-- 【Secondary】データが同期されていることを確認。
SELECT * FROM table1;

コメント

タイトルとURLをコピーしました