環境
2020/9/24にPostgreSQL 13.0がリリースされたのでインストールしてみます。
環境は以下のとおりです。
- CentOS 7.5(firewalldは無効化しています)
- Postgres 13
インストール手順は以下のPostgreSQL12の場合とほぼ同様です。
LLVM関連のライブラリのインストール
12.3からpostgresXX-develをインストールするのにLLVM関連のライブラリが必要となりました。
postgresXX-develは拡張機能をコンパイルするときに使用します。
PostgreSQLを動かすだけなら必ずしもインストールする必要はありません。
# yum -y install epel-release centos-release-scl
PostgreSQLのyumリポジトリをインストール
CentOS用のPostgreSQLのリポジトリパッケージをインストールします。
各OS用のリポジトリパッケージのURL一覧は、以下のサイトに記載されています。
# yum -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
~省略~
Running transaction
  Installing : pgdg-redhat-repo-42.0-13.noarch                                                                                                     1/1 
  Verifying  : pgdg-redhat-repo-42.0-13.noarch                                                                                                     1/1 
Installed:
  pgdg-redhat-repo.noarch 0:42.0-13                                                                                                                    
Complete!
PostgreSQLのインストール
PostgreSQLをインストールします。
※拡張機能をコンパイルするときに使用するので「postgresql13-devel」も一緒を入れていますが、必須ではありません。
# yum -y install postgresql13-contrib postgresql13-devel
~省略~
Installed:
  postgresql13-contrib.x86_64 0:13.0-1PGDG.rhel7                              postgresql13-devel.x86_64 0:13.0-1PGDG.rhel7                             
Dependency Installed:
  audit-libs-python.x86_64 0:2.8.5-4.el7           checkpolicy.x86_64 0:2.5-8.el7                devtoolset-7-binutils.x86_64 0:2.28-11.el7           
  devtoolset-7-gcc.x86_64 0:7.3.1-5.16.el7         devtoolset-7-gcc-c++.x86_64 0:7.3.1-5.16.el7  devtoolset-7-libstdc++-devel.x86_64 0:7.3.1-5.16.el7 
  devtoolset-7-runtime.x86_64 0:7.1-4.el7          libcgroup.x86_64 0:0.41-21.el7                libedit-devel.x86_64 0:3.0-12.20121213cvs.el7        
  libicu.x86_64 0:50.2-4.el7_7                     libicu-devel.x86_64 0:50.2-4.el7_7            libsemanage-python.x86_64 0:2.5-14.el7               
  libxslt.x86_64 0:1.1.28-5.el7                    llvm-toolset-7-clang.x86_64 0:5.0.1-4.el7     llvm-toolset-7-clang-libs.x86_64 0:5.0.1-4.el7       
  llvm-toolset-7-compiler-rt.x86_64 0:5.0.1-2.el7  llvm-toolset-7-libomp.x86_64 0:5.0.1-2.el7    llvm-toolset-7-llvm-libs.x86_64 0:5.0.1-8.el7        
  llvm-toolset-7-runtime.x86_64 0:5.0.1-4.el7      llvm5.0.x86_64 0:5.0.1-7.el7                  llvm5.0-devel.x86_64 0:5.0.1-7.el7                   
  llvm5.0-libs.x86_64 0:5.0.1-7.el7                ncurses-devel.x86_64 0:5.9-14.20130511.el7_4  policycoreutils-python.x86_64 0:2.5-34.el7           
  postgresql13.x86_64 0:13.0-1PGDG.rhel7           postgresql13-libs.x86_64 0:13.0-1PGDG.rhel7   postgresql13-server.x86_64 0:13.0-1PGDG.rhel7        
  python-IPy.noarch 0:0.75-6.el7                   scl-utils.x86_64 0:20130529-19.el7            setools-libs.x86_64 0:3.3.8-4.el7                    
Dependency Updated:
  audit.x86_64 0:2.8.5-4.el7              audit-libs.x86_64 0:2.8.5-4.el7    libselinux.x86_64 0:2.5-15.el7    libselinux-python.x86_64 0:2.5-15.el7   
  libselinux-utils.x86_64 0:2.5-15.el7    libsemanage.x86_64 0:2.5-14.el7    libsepol.x86_64 0:2.5-10.el7      policycoreutils.x86_64 0:2.5-34.el7     
Complete!
PostgreSQLは「/usr/pgsql-13/」以下にインストールされます。
# ls -l /usr/pgsql-13/
total 20
drwxr-xr-x. 2 root root 4096 Sep 25 23:11 bin
drwxr-xr-x. 3 root root   23 Sep 25 23:11 doc
drwxr-xr-x. 6 root root 4096 Sep 25 23:11 include
drwxr-xr-x. 5 root root 4096 Sep 25 23:11 lib
drwxr-xr-x. 8 root root 4096 Sep 25 23:11 share
PostgreSQLの自動起動
PostgreSQLを自動起動させるために以下のコマンドを実行します。
# systemctl enable postgresql-13.service
データベースクラスタの作成
データベースクラスタを作成します。
rootユーザで実行しています。
データベースのファイルはデフォルトで「/var/lib/pgsql/13/data/」に作成されるのですが、これを今回は「/data/」以下に変更しています。
postgresql-13.serviceファイルの「PGDATA」環境変数によって指定できます。
# vi /usr/lib/systemd/system/postgresql-13.service
変更前)
Environment=PGDATA=/var/lib/pgsql/13/data/
変更後)
Environment=PGDATA=/data/
# systemctl daemon-reload
次にデータベースクラスタを作成するために以下のコマンドを実行します。
# PGSETUP_INITDB_OPTIONS="-E UTF8 --no-locale" /usr/pgsql-13/bin/postgresql-13-setup initdb
Initializing database ... OK
「/data/」以下に生成されていることを確認します。
# cat /data/PG_VERSION 
13
PostgreSQLを起動する
起動前にPostgreSQLのbinディレクトリをパスに追加します。
# su - postgres
/var/lib/pgsql/.pgsql_profileにパスを追加します。
# vi /var/lib/pgsql/.pgsql_profile
PATH=/usr/pgsql-13/bin:$PATH
export PATH
PGDATAを修正します。
# vi /var/lib/pgsql/.bash_profile
# PGDATA=/var/lib/pgsql/12/data
PGDATA=/data
# source ~/.bash_profile
PostgreSQLの起動は「pg_ctl start」で行います。
$ pg_ctl start
2020-09-25 23:16:08.611 CEST [12910] HINT:  Future log output will appear in directory "log".
 done
server started
※ "systemctl start postgresql-13"でもOK
データベース確認
作成したデータベースクラスタを確認してみます。
バージョンとデータベースの一覧を表示してみます。
$ psql -V
psql (PostgreSQL) 13.0
$ psql -l
                             List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges   
-----------+----------+----------+---------+-------+-----------------------
 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
(3 rows)
ユーザとデータベースの作成
ユーザ("testuser")とデータベース("testdb")を作成します。
$ createuser --login --pwprompt testuser
Enter password for new role: 
Enter it again:
$ createdb --owner=testuser testdb
外部からの接続を許可する
PostgreSQLはデフォルトではリモート接続できないので、設定を変更します。
# vi /data/postgresql.conf
※デフォルトでは「/var/lib/pgsql/13/data/postgresql.conf」
変更前)
# listen_addresses = 'localhost'
変更後)
listen_addresses = '*'
次にpg_hba.confを修正します。
# vi /data/pg_hba.conf
※デフォルトでは「/var/lib/pgsql/13/data/pg_hba.conf」
# "local" is for Unix domain socket connections only
local   testdb          testuser                                md5
→ローカルからtestdbへtestuserでmd5接続できるように1行追加。
local   all             all                                     peer
# IPv4 local connections:
host    all             all             192.168.10.0/24         md5
→192.168.10.0/24(今回のサーバの環境)から接続できるように1行追加。
host    all             all             127.0.0.1/32            ident
設定変更をリロードします。
$ pg_ctl reload
※ もしくはsystemctl reload postgresql-13でもいいはず。
postgresユーザのパスワードを変更する(変更しなくても良いですが)
$ psql
alter role postgres with password 'postgres';
リモートから接続を確認します(A5:SQLから接続確認しましたが、説明は省略)
ローカルからの接続確認は以下のように実行します。
$ psql testdb testuser
Password for user testuser: 
psql (13.0)
Type "help" for help.
testdb=> 
テーブル作成
テーブルを作成して、データを投入してみます。
testdb=> create table test (id int, value text);
CREATE TABLE
testdb=> insert into test (id, value) values (1, 'test text');
INSERT 0 1
testdb=> select * from test;
 id |   value   
----+-----------
  1 | test text
(1 row)
「\d」でテーブルの一覧、「\du」でロールの一覧を表示します。
testdb=> \d
        List of relations
 Schema | Name | Type  |  Owner   
--------+------+-------+----------
 public | test | table | testuser
(1 row)
testdb=> \du
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 testuser  |                                                            | {}
その他の設定変更
PostgreSQLは全体的に各種パラメータが小さめの値が設定されているように思えます。
共有バッファだけ128MBから512MB(総メモリの20%~40%ぐらいが良いらしい)に変えてみました。それ以外も変えたほうが良いパラメータはたくさんあるのですが、共有バッファも含めてシステム依存なので今回は変更しません。
共有バッファの変更方法は以下のとおりです。
# vi /data/postgresql.conf
※デフォルトでは「/var/lib/pgsql/13/data/postgresql.conf」
変更前)
shared_buffers = 128MB
変更後)
shared_buffers = 512MB
あとはPostgreSQLを再起動するだけです。
ログの設定
ログの設定を以下のように変更しました。
$ vi /data/postgresql.conf
変更前は以下のとおり。
log_filename = 'postgresql-%a.log'
log_rotation_size = 0
# log_min_duration_statement = -1
# log_checkpoints = off
# log_connections = off
# log_disconnections = off
# log_lock_waits = off
変更後は以下のとおり。
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
log_rotation_size = 1GB
log_min_duration_statement = 500ms
log_checkpoints = on
log_connections = on
log_disconnections = on
log_lock_waits = on
log_temp_files = 0
pgbenchでベンチマークを実行する
PostgreSQLではベンチマーク用のツールpgbenchが標準で同梱されています。
まずは、pgbenchでベンチマーク用のテーブルとデータを作成します。
$ pgbench -i -s 10 testdb
dropping old tables...
NOTICE:  table "pgbench_accounts" does not exist, skipping
NOTICE:  table "pgbench_branches" does not exist, skipping
NOTICE:  table "pgbench_history" does not exist, skipping
NOTICE:  table "pgbench_tellers" does not exist, skipping
creating tables...
generating data (client-side)...
1000000 of 1000000 tuples (100%) done (elapsed 9.02 s, remaining 0.00 s)
vacuuming...
creating primary keys...
done in 12.99 s (drop tables 0.00 s, create tables 0.01 s, client-side generate 9.12 s, vacuum 0.87 s, primary keys 3.00 s).
データの準備ができたら、次はベンチマークを実行します。
$ pgbench -c 10 -j 10 -t 2000 -N testdb
starting vacuum...end.
transaction type: <builtin: simple update>
scaling factor: 10
query mode: simple
number of clients: 10
number of threads: 10
number of transactions per client: 2000
number of transactions actually processed: 20000/20000
latency average = 4.910 ms
tps = 2036.732154 (including connections establishing)
tps = 2039.124174 (excluding connections establishing)
"-c 10"はクライアント数が"10"、"-t 1000"は1クライアント当たりのトランザクション数を表します。
ベンチマーク実行後のキャッシュヒット率は以下のように見ることができます。
select relname,
   round(heap_blks_hit * 100 / (heap_blks_hit+heap_blks_read), 2)
   as cache_hit_ratio from pg_statio_user_tables
     where heap_blks_read > 0 order by cache_hit_ratio;
     relname      | cache_hit_ratio 
------------------+-----------------
 test             |           50.00
 pgbench_accounts |           63.00
 pgbench_branches |           82.00
 pgbench_tellers  |           95.00
 pgbench_history  |           99.00
(5 rows)
インデックスのキャッシュヒット率は以下のとおり。
select relname, indexrelname,
   round(idx_blks_hit * 100 / (idx_blks_hit + idx_blks_read), 2)
   as cache_hit_ratio from pg_statio_user_indexes
     where idx_blks_read > 0 order by cache_hit_ratio;
     relname      |     indexrelname      | cache_hit_ratio 
------------------+-----------------------+-----------------
 pgbench_tellers  | pgbench_tellers_pkey  |           33.00
 pgbench_branches | pgbench_branches_pkey |           50.00
 pgbench_accounts | pgbench_accounts_pkey |           98.00
(3 rows)
