LoginSignup
4
4

CentOS8にPostgreSQL14をインストールする手順

Last updated at Posted at 2022-06-26

PostgreSQL14CentOS8にインストールしたので、その時の手順を紹介します。

環境

  • OS:CentOS Linux release 8.5.2111
[root@centos8 ~]# cat /etc/redhat-release
CentOS Linux release 8.5.2111
[root@centos8 ~]#

1. インストール手順

1.1. 概要

インストールの方法は「PostgreSQL: Downloads」のページから調べることができます。
PostgreSQL: Downloads」のページを開き、「Linux」をクリックします。
1-1.png

「Red Hat/Rocky/CentOS」をクリックします。
1-2.png

「1. Select version:」で「14」を選択
「2. Select platform:」で「Red Hat Enterprise, Rocky, or Oracle Version 8」を選択
「3. Select architecture:」で「x86_64」を選択します。
すると、「4. Copy, paste and run the relevant parts of the setup script:」にインストールコマンドが表示されます。
1-3.png

4. Copy, paste and run the relevant parts of the setup script
# Install the repository RPM:
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm

# Disable the built-in PostgreSQL module:
sudo dnf -qy module disable postgresql

# Install PostgreSQL:
sudo dnf install -y postgresql14-server

# Optionally initialize the database and enable automatic start:
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb
sudo systemctl enable postgresql-14
sudo systemctl start postgresql-14

1.2. PostgreSQLのリポジトリRPMのインストール

以下のコマンドでPostgreSQLのリポジトリRPMをインストールします。

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

実行結果
[root@centos8 ~]# dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm
メタデータの期限切れの最終確認: 0:20:54 時間前の 2022年05月27日 23時10分13秒 に実施しました。
pgdg-redhat-repo-latest.noarch.rpm                                                                                      10 kB/s |  13 kB     00:01
依存関係が解決しました。
=======================================================================================================================================================
 パッケージ                               アーキテクチャー               バージョン                         リポジトリー                         サイズ
=======================================================================================================================================================
インストール:
 pgdg-redhat-repo                         noarch                         42.0-24                            @commandline                          13 k

トランザクションの概要
=======================================================================================================================================================
インストール  1 パッケージ

合計サイズ: 13 k
インストール後のサイズ: 12 k
パッケージのダウンロード:
トランザクションの確認を実行中
トランザクションの確認に成功しました。
トランザクションのテストを実行中
トランザクションのテストに成功しました。
トランザクションを実行中
  準備             :                                                                                                                               1/1
  インストール中   : pgdg-redhat-repo-42.0-24.noarch                                                                                               1/1
  検証             : pgdg-redhat-repo-42.0-24.noarch                                                                                               1/1

インストール済み:
  pgdg-redhat-repo-42.0-24.noarch

完了しました!
[root@centos8 ~]#

1.3. 組み込みPostgreSQLモジュールを無効化

以下のコマンドで、CentOS標準の組み込みのPostgreSQLモジュールを無効化します。

dnf -qy module disable postgresql

実行結果
[root@centos8 ~]# dnf -y module disable postgresql
PostgreSQL common RPMs for RHEL / Rocky 8 - x86_64                                                                      85  B/s | 195  B     00:02
PostgreSQL common RPMs for RHEL / Rocky 8 - x86_64                                                                     1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
PostgreSQL common RPMs for RHEL / Rocky 8 - x86_64                                                                     148 kB/s | 621 kB     00:04
PostgreSQL 14 for RHEL / Rocky 8 - x86_64                                                                               95  B/s | 195  B     00:02
PostgreSQL 14 for RHEL / Rocky 8 - x86_64                                                                              1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
PostgreSQL 14 for RHEL / Rocky 8 - x86_64                                                                               69 kB/s | 278 kB     00:04
PostgreSQL 13 for RHEL / Rocky 8 - x86_64                                                                               94  B/s | 195  B     00:02
PostgreSQL 13 for RHEL / Rocky 8 - x86_64                                                                              1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
PostgreSQL 13 for RHEL / Rocky 8 - x86_64                                                                              139 kB/s | 593 kB     00:04
PostgreSQL 12 for RHEL / Rocky 8 - x86_64                                                                               94  B/s | 195  B     00:02
PostgreSQL 12 for RHEL / Rocky 8 - x86_64                                                                              1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
PostgreSQL 12 for RHEL / Rocky 8 - x86_64                                                                              178 kB/s | 757 kB     00:04
PostgreSQL 11 for RHEL / Rocky 8 - x86_64                                                                               94  B/s | 195  B     00:02
PostgreSQL 11 for RHEL / Rocky 8 - x86_64                                                                              1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
PostgreSQL 11 for RHEL / Rocky 8 - x86_64                                                                              211 kB/s | 952 kB     00:04
PostgreSQL 10 for RHEL / Rocky 8 - x86_64                                                                               92  B/s | 195  B     00:02
PostgreSQL 10 for RHEL / Rocky 8 - x86_64                                                                              1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
PostgreSQL 10 for RHEL / Rocky 8 - x86_64                                                                              149 kB/s | 631 kB     00:04
依存関係が解決しました。
=======================================================================================================================================================
 パッケージ                          アーキテクチャー                   バージョン                           リポジトリー                        サイズ
=======================================================================================================================================================
モジュールの無効化:
 postgresql

トランザクションの概要
=======================================================================================================================================================

完了しました!
[root@centos8 ~]#

以下のコマンドでインストールしたPostgreSQLのリポジトリを確認します。

dnf search postgresql*-server

実行結果
[root@centos8 ~]# dnf search postgresql*-server
メタデータの期限切れの最終確認: 0:03:07 時間前の 2022年05月27日 23時33分37秒 に実施しました。
============================================================ 名前 一致: postgresql*-server ============================================================
postgresql10-server.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql11-server.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql12-server.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql13-server.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql14-server.x86_64 : The programs needed to create and run a PostgreSQL server
[root@centos8 ~]#

PostgreSQLのバージョン10, 11, 12, 13, 14が含まれています。

1.4. PostgreSQL 14をインストール

以下のコマンドでPostgreSQL 14をインストールします。

dnf install -y postgresql14-server

実行結果
[root@centos8 ~]# dnf install -y postgresql14-server
メタデータの期限切れの最終確認: 0:04:53 時間前の 2022年05月27日 23時33分37秒 に実施しました。
依存関係が解決しました。
=======================================================================================================================================================
 パッケージ                                 アーキテクチャー              バージョン                               リポジトリー                  サイズ
=======================================================================================================================================================
インストール:
 postgresql14-server                        x86_64                        14.3-1PGDG.rhel8                         pgdg14                        5.7 M
依存関係のインストール:
 postgresql14                               x86_64                        14.3-1PGDG.rhel8                         pgdg14                        1.5 M
 postgresql14-libs                          x86_64                        14.3-1PGDG.rhel8                         pgdg14                        276 k

トランザクションの概要
=======================================================================================================================================================
インストール  3 パッケージ

ダウンロードサイズの合計: 7.5 M
インストール後のサイズ: 31 M
パッケージのダウンロード:
(1/3): postgresql14-libs-14.3-1PGDG.rhel8.x86_64.rpm                                                                   141 kB/s | 276 kB     00:01
(2/3): postgresql14-14.3-1PGDG.rhel8.x86_64.rpm                                                                        576 kB/s | 1.5 MB     00:02
(3/3): postgresql14-server-14.3-1PGDG.rhel8.x86_64.rpm                                                                 1.1 MB/s | 5.7 MB     00:04
-------------------------------------------------------------------------------------------------------------------------------------------------------
合計                                                                                                                   1.5 MB/s | 7.5 MB     00:05
PostgreSQL 14 for RHEL / Rocky 8 - x86_64                                                                              1.6 MB/s | 1.7 kB     00:00
GPG 鍵 0x442DF0F8 をインポート中:
 Userid     : "PostgreSQL RPM Building Project <pgsql-pkg-yum@postgresql.org>"
 Fingerprint: 68C9 E2B9 1A37 D136 FE74 D176 1F16 D2E1 442D F0F8
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG
鍵のインポートに成功しました
トランザクションの確認を実行中
トランザクションの確認に成功しました。
トランザクションのテストを実行中
トランザクションのテストに成功しました。
トランザクションを実行中
  準備             :                                                                                                                               1/1
  インストール中   : postgresql14-libs-14.3-1PGDG.rhel8.x86_64                                                                                     1/3
  scriptletの実行中: postgresql14-libs-14.3-1PGDG.rhel8.x86_64                                                                                     1/3
  インストール中   : postgresql14-14.3-1PGDG.rhel8.x86_64                                                                                          2/3
  scriptletの実行中: postgresql14-14.3-1PGDG.rhel8.x86_64                                                                                          2/3
  scriptletの実行中: postgresql14-server-14.3-1PGDG.rhel8.x86_64                                                                                   3/3
  インストール中   : postgresql14-server-14.3-1PGDG.rhel8.x86_64                                                                                   3/3
  scriptletの実行中: postgresql14-server-14.3-1PGDG.rhel8.x86_64                                                                                   3/3
[/usr/lib/tmpfiles.d/pesign.conf:1] Line references path below legacy directory /var/run/, updating /var/run/pesign → /run/pesign; please update the tmpfiles.d/ drop-in file accordingly.

  検証             : postgresql14-14.3-1PGDG.rhel8.x86_64                                                                                          1/3
  検証             : postgresql14-libs-14.3-1PGDG.rhel8.x86_64                                                                                     2/3
  検証             : postgresql14-server-14.3-1PGDG.rhel8.x86_64                                                                                   3/3

インストール済み:
  postgresql14-14.3-1PGDG.rhel8.x86_64          postgresql14-libs-14.3-1PGDG.rhel8.x86_64          postgresql14-server-14.3-1PGDG.rhel8.x86_64

完了しました!
[root@centos8 ~]#

1.5. マニュアル参照を設定

manコマンドで PostgreSQL のマニュアルを参照できるように/etc/man_db.confに以下を追加します。
MANDATORY_MANPATH /usr/pgsql-14/share/man/

/etc/man_db.conf
~~ 省略 ~~
# every automatically generated MANPATH includes these fields
#
#MANDATORY_MANPATH                      /usr/src/pvm3/man
#
MANDATORY_MANPATH                       /usr/man
MANDATORY_MANPATH                       /usr/share/man
MANDATORY_MANPATH                       /usr/local/share/man
MANDATORY_MANPATH                       /usr/pgsql-14/share/man/
~~ 省略 ~~

これにより、man psqlman initdbのように、manコマンドで PostgreSQL のコマンドを参照できるようになります。

1.6. 環境変数の確認

postgresユーザーにスイッチし、PGDATAの値を確認します。デフォルトでは/var/lib/pgsql/14/dataになっています。

su - postgres
env | grep PGDATA

実行結果
[root@centos8 ~]# su - postgres
[postgres@centos8 ~]$ env | grep PGDATA
PGDATA=/var/lib/pgsql/14/data
[postgres@centos8 ~]$ exit
ログアウト
[root@centos8 ~]#

なお、PGDATApostgresユーザーのホームディレクトリ/var/lib/pgsql配下の.bash_profileに設定されています。

/var/lib/pgsql/.bash_profile
[ -f /etc/profile ] && source /etc/profile
PGDATA=/var/lib/pgsql/14/data
export PGDATA
# If you want to customize your settings,
# Use the file below. This is not overridden
# by the RPMS.
[ -f /var/lib/pgsql/.pgsql_profile ] && source /var/lib/pgsql/.pgsql_profile

1.7. データベースの初期化(データベースクラスタの作成)

以下のコマンドで、データベースの初期化(データベースクラスタの作成)を行います。
PGSETUP_INITDB_OPTIONSの環境変数で、エンコーディングを「UTF-8」に、ロケールを「無し」に設定しています。)
なお、データベースクラスタはPGDATAで指定されているディレクトリに作成されます。

PGSETUP_INITDB_OPTIONS='--encoding=UTF-8 --no-locale' /usr/pgsql-14/bin/postgresql-14-setup initdb

実行結果
[root@centos8 ~]# PGSETUP_INITDB_OPTIONS='--encoding=UTF-8 --no-locale' /usr/pgsql-14/bin/postgresql-14-setup initdb
Initializing database ... OK

[root@centos8 ~]#

PGDATA/var/lib/pgsql/14/dataを参照すると、以下の通りデータベースクラスタが作成されています。

実行結果
[root@centos8 ~]# ls -l /var/lib/pgsql/14/data
合計 64
-rw------- 1 postgres postgres     3  5月 28 01:17 PG_VERSION
drwx------ 5 postgres postgres    41  5月 28 01:17 base
-rw------- 1 postgres postgres    30  5月 29 02:39 current_logfiles
drwx------ 2 postgres postgres  4096  5月 29 02:39 global
drwx------ 2 postgres postgres    58  5月 29 02:39 log
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_commit_ts
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_dynshmem
-rw------- 1 postgres postgres  4577  5月 28 01:17 pg_hba.conf
-rw------- 1 postgres postgres  1636  5月 28 01:17 pg_ident.conf
drwx------ 4 postgres postgres    68  5月 29 03:19 pg_logical
drwx------ 4 postgres postgres    36  5月 28 01:17 pg_multixact
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_notify
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_replslot
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_serial
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_snapshots
drwx------ 2 postgres postgres    63  5月 29 03:19 pg_stat
drwx------ 2 postgres postgres     6  5月 29 03:19 pg_stat_tmp
drwx------ 2 postgres postgres    18  5月 28 01:17 pg_subtrans
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_tblspc
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_twophase
drwx------ 3 postgres postgres    60  5月 28 01:17 pg_wal
drwx------ 2 postgres postgres    18  5月 28 01:17 pg_xact
-rw------- 1 postgres postgres    88  5月 28 01:17 postgresql.auto.conf
-rw------- 1 postgres postgres 28724  5月 28 01:17 postgresql.conf
-rw------- 1 postgres postgres    58  5月 29 02:39 postmaster.opts
[root@centos8 ~]#

2. PostgreSQLの起動、停止、自動起動有効化

PostgreSQLのサービスのユニット定義ファイルは/usr/lib/systemd/system/postgresql-14.serviceに作成されています。

/usr/lib/systemd/system/postgresql-14.service
# It's not recommended to modify this file in-place, because it will be
# overwritten during package upgrades.  It is recommended to use systemd
# "dropin" feature;  i.e. create file with suffix .conf under
# /etc/systemd/system/postgresql-14.service.d directory overriding the
# unit's defaults. You can also use "systemctl edit postgresql-14"
# Look at systemd.unit(5) manual page for more info.

# Note: changing PGDATA will typically require adjusting SELinux
# configuration as well.

# Note: do not use a PGDATA pathname containing spaces, or you will
# break postgresql-14-setup.
[Unit]
Description=PostgreSQL 14 database server
Documentation=https://www.postgresql.org/docs/14/static/
After=syslog.target
After=network.target

[Service]
Type=notify

User=postgres
Group=postgres

# Note: avoid inserting whitespace in these Environment= lines, or you may
# break postgresql-setup.

# Location of database directory
Environment=PGDATA=/var/lib/pgsql/14/data/

# Where to send early-startup messages from the server (before the logging
# options of postgresql.conf take effect)
# This is normally controlled by the global default set by systemd
# StandardOutput=syslog

# Disable OOM kill on the postmaster
OOMScoreAdjust=-1000
Environment=PG_OOM_ADJUST_FILE=/proc/self/oom_score_adj
Environment=PG_OOM_ADJUST_VALUE=0

ExecStartPre=/usr/pgsql-14/bin/postgresql-14-check-db-dir ${PGDATA}
ExecStart=/usr/pgsql-14/bin/postmaster -D ${PGDATA}
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
KillSignal=SIGINT

# Do not set any timeout value, so that systemd will not kill postmaster
# during crash recovery.
TimeoutSec=0

# 0 is the same as infinity, but "infinity" needs systemd 229
TimeoutStartSec=0

TimeoutStopSec=1h

[Install]
WantedBy=multi-user.target

Environment=PGDATA=/var/lib/pgsql/14/data/と「PGDATA」には「/var/lib/pgsql/14/data/」が設定されています。
(「PGDATA」を変更している場合、上記のファイルも変更する必要があります。)

PostgreSQLの起動、停止、自動起動有効化は以下のコマンドとなります。

  • 起動
    systemctl start postgresql-14

  • 停止
    systemctl stop postgresql-14

  • 自動起動有効化
    systemctl enable postgresql-14

3. 動作確認用DBの作成

3.1. PostgreSQL起動

systemctl start postgresql-14のコマンドでPostgreSQLを起動します。

実行結果
[root@centos8 ~]# systemctl start postgresql-14
[root@centos8 ~]#

3.2. psqlで接続

postgresユーザーにスイッチし、psqlコマンドでデータベースに接続します。
su - postgres
psql

実行結果
[root@centos8 ~]# su - postgres
[postgres@centos8 ~]$ psql
psql (14.3)
"help"でヘルプを表示します。

postgres=#

以下のSQLでバージョンを確認してみます。
select version();

実行結果
postgres=# select version();
                                                 version

--------------------------------------------------------------------------------
-------------------------
 PostgreSQL 14.3 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.5.0 20210514 (R
ed Hat 8.5.0-10), 64-bit
(1 )

postgres=#

3.3. ロールの作成

以下のSQLでロール(test_role)を作成します。

CREATE ROLE test_role WITH
  SUPERUSER
  CREATEDB
  CREATEROLE
  INHERIT
  LOGIN
  REPLICATION
  BYPASSRLS
  ENCRYPTED PASSWORD 'password';
実行結果
postgres=# CREATE ROLE test_role WITH
postgres-#   SUPERUSER
postgres-#   CREATEDB
postgres-#   CREATEROLE
postgres-#   INHERIT
postgres-#   LOGIN
postgres-#   REPLICATION
postgres-#   BYPASSRLS
postgres-#   ENCRYPTED PASSWORD 'password';
CREATE ROLE
postgres=#

\duコマンドでロールの一覧を参照し、ロール(test_role)が作成されていることを確認します。

実行結果
postgres=# \du
ロール一覧
-[ RECORD 1 ]+-----------------------------------------------------------------------------
ロール名     | postgres
属性         | スーパーユーザー, ロール作成可, DB作成可, レプリケーション可, RLS のバイパス
所属グループ | {}
-[ RECORD 2 ]+-----------------------------------------------------------------------------
ロール名     | test_role
属性         | スーパーユーザー, ロール作成可, DB作成可, レプリケーション可, RLS のバイパス
所属グループ | {}

postgres=#

3.4. テーブルスペース作成

\qコマンドで、一旦psqlから抜けます。

実行結果
postgres=# \q
[postgres@centos8 ~]$

以下のコマンドでテーブルスペース(test_tbs)で使用するディレクトリを作成します。
mkdir /var/lib/pgsql/14/data/test_tbs

実行結果
[postgres@centos8 ~]$ mkdir /var/lib/pgsql/14/data/test_tbs
[postgres@centos8 ~]$ ls -l /var/lib/pgsql/14/data
合計 68
-rw------- 1 postgres postgres     3  5月 28 01:17 PG_VERSION
drwx------ 5 postgres postgres    41  5月 28 01:17 base
-rw------- 1 postgres postgres    30  6月 26 14:45 current_logfiles
drwx------ 2 postgres postgres  4096  6月 26 14:45 global
drwx------ 2 postgres postgres    58  5月 29 02:39 log
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_commit_ts
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_dynshmem
-rw------- 1 postgres postgres  4577  5月 28 01:17 pg_hba.conf
-rw------- 1 postgres postgres  1636  5月 28 01:17 pg_ident.conf
drwx------ 4 postgres postgres    68  6月 26 14:55 pg_logical
drwx------ 4 postgres postgres    36  5月 28 01:17 pg_multixact
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_notify
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_replslot
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_serial
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_snapshots
drwx------ 2 postgres postgres     6  6月 26 14:45 pg_stat
drwx------ 2 postgres postgres    63  6月 26 15:03 pg_stat_tmp
drwx------ 2 postgres postgres    18  5月 28 01:17 pg_subtrans
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_tblspc
drwx------ 2 postgres postgres     6  5月 28 01:17 pg_twophase
drwx------ 3 postgres postgres    60  5月 28 01:17 pg_wal
drwx------ 2 postgres postgres    18  5月 28 01:17 pg_xact
-rw------- 1 postgres postgres    88  5月 28 01:17 postgresql.auto.conf
-rw------- 1 postgres postgres 28724  5月 28 01:17 postgresql.conf
-rw------- 1 postgres postgres    58  6月 26 14:45 postmaster.opts
-rw------- 1 postgres postgres   103  6月 26 14:45 postmaster.pid
drwxr-xr-x 2 postgres postgres     6  6月 26 15:03 test_tbs
[postgres@centos8 ~]$

再度、psqlコマンドでデータベースに接続します。

実行結果
[postgres@centos8 ~]$ psql
psql (14.3)
"help"でヘルプを表示します。

postgres=#

以下のSQLで、テーブルスペース(test_tbs)を作成します。

CREATE TABLESPACE test_tbs
  OWNER test_role
  LOCATION '/var/lib/pgsql/14/data/test_tbs';
COMMENT ON TABLESPACE test_tbs IS 'テスト用テーブルスペース';
GRANT CREATE ON TABLESPACE test_tbs TO test_role;
実行結果
postgres=# CREATE TABLESPACE test_tbs
postgres-#   OWNER test_role
postgres-#   LOCATION '/var/lib/pgsql/14/data/test_tbs';
WARNING:  tablespace location should not be inside the data directory
CREATE TABLESPACE
postgres=# COMMENT ON TABLESPACE test_tbs IS 'テスト用テーブルスペース';
COMMENT
postgres=# GRANT CREATE ON TABLESPACE test_tbs TO test_role;
GRANT
postgres=#

\dbでテーブルスペース(test_tbs)が作成されていることを確認します。

実行結果
postgres=# \db
                     テーブル空間一覧
    名前    |  所有者   |              場所
------------+-----------+---------------------------------
 pg_default | postgres  |
 pg_global  | postgres  |
 test_tbs   | test_role | /var/lib/pgsql/14/data/test_tbs
(3 )

postgres=#

3.5. データベース作成

以下のSQLでデーターベース(test_db)を作成します。

CREATE DATABASE test_db
    WITH 
    OWNER = test_role
    ENCODING = 'UTF8'
    LC_COLLATE = 'C'
    LC_CTYPE = 'C'
    TABLESPACE = test_tbs
    ALLOW_CONNECTIONS = true
    CONNECTION LIMIT = -1;
COMMENT ON DATABASE test_db IS 'テスト用データベース';
実行結果
postgres=# CREATE DATABASE test_db
postgres-#     WITH
postgres-#     OWNER = test_role
postgres-#     ENCODING = 'UTF8'
postgres-#     LC_COLLATE = 'C'
postgres-#     LC_CTYPE = 'C'
postgres-#     TABLESPACE = test_tbs
postgres-#     ALLOW_CONNECTIONS = true
postgres-#     CONNECTION LIMIT = -1;
CREATE DATABASE
postgres=# COMMENT ON DATABASE test_db IS 'テスト用データベース';
COMMENT
postgres=#

\lコマンドでデーターベースの一覧を参照し、データベース(test_db)が作成されていることを確認します。

実行結果
postgres=# \l
                                        データベース一覧
   名前    |  所有者   | エンコーディング | 照合順序 | Ctype(変換演算子) |     アクセス権限
-----------+-----------+------------------+----------+-------------------+-----------------------
 postgres  | postgres  | UTF8             | C        | C                 |
 template0 | postgres  | UTF8             | C        | C                 | =c/postgres          +
           |           |                  |          |                   | postgres=CTc/postgres
 template1 | postgres  | UTF8             | C        | C                 | =c/postgres          +
           |           |                  |          |                   | postgres=CTc/postgres
 test_db   | test_role | UTF8             | C        | C                 |
(4 )

postgres=#

3.6. スキーマ作成

\c test_dbコマンドで、test_dbに切り替えます。

実行結果
postgres=# \c test_db
データベース"test_db"にユーザー"postgres"として接続しました。
test_db=#

以下のSQLで``test_dbに、スキーマ(test_schema`)を作成します。

CREATE SCHEMA test_schema AUTHORIZATION test_role;
COMMENT ON SCHEMA test_schema IS 'テスト用スキーマ';
GRANT ALL ON SCHEMA test_schema TO test_role;
実行結果
test_db=# CREATE SCHEMA test_schema AUTHORIZATION test_role;
CREATE SCHEMA
test_db=# COMMENT ON SCHEMA test_schema IS 'テスト用スキーマ';
COMMENT
test_db=# GRANT ALL ON SCHEMA test_schema TO test_role;
GRANT
test_db=#

\dn+コマンドでスキーマの一覧を参照し、スキーマ(test_schema)が作成されていることを確認します。

実行結果
test_db=# \dn+
                               スキーマ一覧
    名前     |  所有者   |      アクセス権限      |          説明
-------------+-----------+------------------------+------------------------
 public      | postgres  | postgres=UC/postgres  +| standard public schema
             |           | =UC/postgres           |
 test_schema | test_role | test_role=UC/test_role | テスト用スキーマ
(2 )

test_db=#

ここでは、スキーマとしてtest_schemaを作成しましたが、postgresql.confsearch_path'"$user", public'が設定されているため、スキーマはデフォルトのpublicを使用するか、ユーザー(ロール)と同じ名前にしたほうが使い勝手がよさそうです。

設定確認
[postgres@centos8 ~]$ grep search_path /var/lib/pgsql/14/data/postgresql.conf
#search_path = '"$user", public'        # schema names
[postgres@centos8 ~]$

3.7. テーブルとインデックスの作成

以下のSQLでtest_dbtest_schemaにテーブル(test_table)を作成します。

CREATE TABLE test_schema.test_table (
  test_id varchar(8), 
  test_name varchar(256),
  PRIMARY KEY (test_id)
) TABLESPACE test_tbs;
COMMENT ON TABLE test_table IS 'テスト用テーブル';
実行結果
test_db=# CREATE TABLE test_schema.test_table (
test_db(#   test_id varchar(8),
test_db(#   test_name varchar(256),
test_db(#   PRIMARY KEY (test_id)
test_db(# ) TABLESPACE test_tbs;
CREATE TABLE
test_db=# COMMENT ON TABLE test_table IS 'テスト用テーブル';
ERROR:  relation "test_table" does not exist
test_db=#

\dt test_schema.*コマンドで、テーブル(test_table)が作成されていることを確認します。

実行結果
test_db=# \dt test_schema.*
                リレーション一覧
  スキーマ   |    名前    |  タイプ  |  所有者
-------------+------------+----------+----------
 test_schema | test_table | テーブル | postgres
(1 )

test_db=#

以下のSQLでtest_tableにデータを投入します。

INSERT INTO test_schema.test_table(test_id, test_name) VALUES('00000001', 'テスト名称1');
INSERT INTO test_schema.test_table(test_id, test_name) VALUES('00000002', 'テスト名称2');
実行結果
test_db=# INSERT INTO test_schema.test_table(test_id, test_name) VALUES('00000001', 'テスト名称1');
INSERT 0 1
test_db=# INSERT INTO test_schema.test_table(test_id, test_name) VALUES('00000002', 'テスト名称2');
INSERT 0 1
test_db=#

以下のSQLでtest_tableを参照します。
select * from test_schema.test_table;

実行結果
test_db=# select * from test_schema.test_table;
 test_id  |  test_name
----------+--------------
 00000001 | テスト名称1
 00000002 | テスト名称2
(2 )

test_db=#

\qコマンドでpsqlから抜けます。

実行結果
test_db=# \q
[postgres@centos8 ~]$

4. ネットワーク設定(クライアント端末から接続のため)

4.1. postgresql.confの修正

/var/lib/pgsql/14/data/postgresql.conflisten_addressesportの項目を修正します。
listen_addressesには接続を受け付けるサーバー側のIPアドレスを設定します。(ここではPostgreSQLをインストールしたサーバーのIPアドレスの192.168.1.10
portには接続を受け付けるサーバー側のポートを設定します。(PostgreSQLのポートである5432

/var/lib/pgsql/14/data/postgresql.conf(変更前)
~~ 省略 ~~
#listen_addresses = 'localhost'         # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
                                        # (change requires restart)
#port = 5432                            # (change requires restart)
~~ 省略 ~~
/var/lib/pgsql/14/data/postgresql.conf(変更後)
~~ 省略 ~~
listen_addresses = '192.168.0.10'       # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
                                        # (change requires restart)
port = 5432                             # (change requires restart)
~~ 省略 ~~

4.2. pg_hba.confの修正

/var/lib/pgsql/14/data/pg_hba.confに以下の設定を追加します。

  • TYPE: host
  • DATABASE: test_db
  • USER: test_role
  • ADDRESS: 192.168.0.0/24
  • METHOD: scram-sha-256

192.168.0.0/24はサーバーに接続するクライアントのネットワークアドレスです。

/var/lib/pgsql/14/data/pg_hba.conf(追加)
host    test_db         test_role       192.168.0.0/24          scram-sha-256

4.3. PostgreSQLの再起動

su -コマンドでrootユーザーにスイッチします。

実行結果
[postgres@centos8 data]$ su -
パスワード:
[root@centos8 ~]#

systemctl restart postgresql-14コマンドでPostgreSQLを再起動します。

実行結果
[root@centos8 ~]# systemctl restart postgresql-14
[root@centos8 ~]#

4.4. firewallの設定

/usr/lib/firewalld/services/postgresql.xmlのファイルが存在することを確認します。

/usr/lib/firewalld/services/postgresql.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>PostgreSQL</short>
  <description>PostgreSQL Database Server</description>
  <port protocol="tcp" port="5432"/>
</service>

以下のコマンドでfirewall にpostgresqlのサービスを追加します。
firewall-cmd --add-service=postgresql --permanent --zone=public

実行結果
[root@centos8 ~]# firewall-cmd --add-service=postgresql --permanent --zone=public
success
[root@centos8 ~]#

以下のコマンドで firewall を再起動します。
systemctl restart firewalld.service

実行結果
[root@centos8 ~]# systemctl restart firewalld.service
[root@centos8 ~]#

以下のコマンドで、firewall にpostgresqlが追加されていることを確認します。
firewall-cmd --list-services --zone=public

実行結果
[root@centos8 ~]# firewall-cmd --list-services --zone=public
cockpit dhcpv6-client postgresql ssh
[root@centos8 ~]#

5. A5M2.exe で接続確認

クライアント端末(ここではWindowsPC)で A5M2.exe を起動します。
A5M2.exe は「A5:SQL Mk-2 - フリーのSQLクライアント/ER図作成ソフト (松原正和)」からダウンロードできます。

メニューから「データベース」-「データベースの追加と削除」を選択します。
5-1.png

「追加」をクリックします。
5-2.png

「PostgreSQL(直接接続)」をクリックします。
5-3.png

以下を入力し、「OK」をクリックします。

  • サーバー名: サーバのIPアドレス(ここでは192.168.0.10
  • データベース名: test_db
  • ユーザーID: test_role
  • パスワード: password
  • パスワードを保存する: チェック
    5-4.png

そのまま「OK」をクリックします。
5-5.png

「閉じる」をクリックします。
5-6.png

「test_db」をクリックします。
5-7.png

「接続」をクリックします。
5-8.png

「test_db」-「test_schema」-「test_table」を選択し、テーブルが参照できることを確認できました。
5-9.png

参考

4
4
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
4
4