GCEにPostgreSQLを構築する

前提

GCEにCentOS Stream 8のVPSが構築済である事。
ローカルから接続したい場合、GCEのファイアウォールを設定して、5432のportを開けておく必要があります。
GCEの設定については過去記事を参考。

リポジトリに登録

sudo dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
rpm -qi pgdg-redhat-repo

PostgreSQL11のインストール

sudo dnf -y module disable postgresql
sudo dnf clean all
sudo dnf -y install postgresql11-server postgresql11
dnf -y info postgresql11-server postgresql11

初期化

sudo /usr/pgsql-11/bin/postgresql-11-setup initdb

自動起動

sudo systemctl enable --now postgresql-11

postgresql.confの設定

sudo vi /var/lib/pgsql/11/data/postgresql.conf
#listen_addresses = 'localhost'
↓
listen_addresses = '*'

pg_hba.confの設定

sudo vi /var/lib/pgsql/11/data/pg_hba.conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
# IPv6 local connections:
host    all             all             ::1/128                 ident
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 ident

↓

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             0.0.0.0/0               trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
# local   replication     all                                     peer
# host    replication     all             127.0.0.1/32            ident
# host    replication     all             ::1/128                 ident

PostgreSQLの再起動

sudo systemctl restart postgresql-11

エラーになる場合は下記で権限を設定後、再度PostgreSQLの再起動のコマンドを実行してください。

sudo chmod 700 /var/lib/pgsql/11/data

GCEのrootパスワードを設定

sudo passwd root
# rootのパスワードを設定

Postgresのパスワードを設定

su
# 先ほど設定したrootのパスワードを入力
su - postgres
psql -U postgres
\password
# Postgresのパスワードを設定