LoginSignup
19
23

More than 3 years have passed since last update.

CentOS 7.5にPostgreSQL12をインストールする

Last updated at Posted at 2019-10-10

環境

CentOS 7.5にPostgreSQL12をインストールした際のメモです。
環境は以下のとおりです。

  • CentOS 7.5(firewalldは無効化しています)
  • Postgres 12

インストール手順は以下のPostgreSQL11.2の場合とほぼ同様です。

[2020/6/10補足]
本手順はマイナーバージョンを指定していないため、最新バージョンのPostgreSQLがインストールされます。2020年6月時点では12.3がインストールされます。

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-5.noarch                                                                                      1/1 
  Verifying  : pgdg-redhat-repo-42.0-5.noarch                                                                                      1/1 

Installed:
  pgdg-redhat-repo.noarch 0:42.0-5                                                                                                     

Complete!

PostgreSQLのインストール

PostgreSQLをインストールします。
※拡張機能をコンパイルするときに使用するので「postgresql12-devel」も一緒を入れておいても良いです。

# yum -y install postgresql12-server postgresql12-contrib

~省略~
Installed:
  postgresql12-contrib.x86_64 0:12.0-1PGDG.rhel7           postgresql12-server.x86_64 0:12.0-1PGDG.rhel7          

Dependency Installed:
  libicu.x86_64 0:50.2-3.el7                                 libtirpc.x86_64 0:0.2.4-0.16.el7                     
  libxslt.x86_64 0:1.1.28-5.el7                              postgresql12.x86_64 0:12.0-1PGDG.rhel7               
  postgresql12-libs.x86_64 0:12.0-1PGDG.rhel7                python3.x86_64 0:3.6.8-10.el7                        
  python3-libs.x86_64 0:3.6.8-10.el7                         python3-pip.noarch 0:9.0.3-5.el7                     
  python3-setuptools.noarch 0:39.2.0-10.el7                 

Dependency Updated:
  python.x86_64 0:2.7.5-86.el7                          python-libs.x86_64 0:2.7.5-86.el7                         

Complete!

PostgreSQLは「/usr/pgsql-12/」以下にインストールされます。

# ls -l /usr/pgsql-12/
total 16
drwxr-xr-x. 2 root root 4096 Oct 10 13:42 bin
drwxr-xr-x. 3 root root   23 Oct 10 13:42 doc
drwxr-xr-x. 3 root root 4096 Oct 10 13:42 lib
drwxr-xr-x. 8 root root 4096 Oct 10 13:42 share

PostgreSQLの自動起動

PostgreSQLを自動起動させるために以下のコマンドを実行します。

# systemctl enable postgresql-12.service

データベースクラスタの作成

データベースクラスタを作成します。
rootユーザで実行しています。
データベースのファイルはデフォルトで「/var/lib/pgsql/12/data/」に作成されるのですが、これを「/data/」以下に変更します。
postgresql-12.serviceファイルの「PGDATA」環境変数によって指定できます。

# vi /usr/lib/systemd/system/postgresql-12.service

変更前)
Environment=PGDATA=/var/lib/pgsql/12/data/
変更後)
Environment=PGDATA=/data/

# systemctl daemon-reload

次にデータベースクラスタを作成するために以下のコマンドを実行します。

# PGSETUP_INITDB_OPTIONS="-E UTF8 --no-locale" /usr/pgsql-12/bin/postgresql-12-setup initdb
Initializing database ... OK

「/data/」以下に生成されていることを確認します。

# cat /data/PG_VERSION 
12

PostgreSQLを起動する

起動前にPostgreSQLのbinディレクトリをパスに追加します。

# su - postgres

/var/lib/pgsql/.pgsql_profileにパスを追加します。

# vi /var/lib/pgsql/.pgsql_profile
PATH=/usr/pgsql-12/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
waiting for server to start....2019-10-10 13:54:19.061 CEST [12763] LOG:  starting PostgreSQL 12.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
2019-10-10 13:54:19.063 CEST [12763] LOG:  listening on IPv6 address "::1", port 5432
2019-10-10 13:54:19.063 CEST [12763] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2019-10-10 13:54:19.065 CEST [12763] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2019-10-10 13:54:19.067 CEST [12763] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2019-10-10 13:54:19.073 CEST [12763] LOG:  redirecting log output to logging collector process
2019-10-10 13:54:19.073 CEST [12763] HINT:  Future log output will appear in directory "log".
 done
server started

※ "systemctl start postgresql-12"でもOK

データベース確認

作成したデータベースクラスタを確認してみます。
バージョンとデータベースの一覧を表示してみます。

$ psql -V
psql (PostgreSQL) 12.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/12/data/postgresql.conf」

変更前)
#listen_addresses = 'localhost'
変更後)
listen_addresses = '*'

次にpg_hba.confを修正します。

# vi /data/pg_hba.conf
※デフォルトでは「/var/lib/pgsql/12/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-12でもいいはず。

postgresユーザのパスワードを変更する(変更しなくても良いですが)

$ psql
alter role postgres with password 'postgres';

リモートから接続を確認します(A5:SQLから接続確認しましたが、説明は省略)

ローカルからの接続確認は以下のように実行します。

$ psql testdb testuser

Password for user testuser: 
psql (12.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/12/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...
creating tables...
generating data...
100000 of 1000000 tuples (10%) done (elapsed 0.11 s, remaining 1.00 s)
200000 of 1000000 tuples (20%) done (elapsed 0.22 s, remaining 0.88 s)
300000 of 1000000 tuples (30%) done (elapsed 0.35 s, remaining 0.83 s)
400000 of 1000000 tuples (40%) done (elapsed 0.49 s, remaining 0.73 s)
500000 of 1000000 tuples (50%) done (elapsed 0.60 s, remaining 0.60 s)
600000 of 1000000 tuples (60%) done (elapsed 0.74 s, remaining 0.49 s)
700000 of 1000000 tuples (70%) done (elapsed 0.88 s, remaining 0.38 s)
800000 of 1000000 tuples (80%) done (elapsed 1.05 s, remaining 0.26 s)
900000 of 1000000 tuples (90%) done (elapsed 1.22 s, remaining 0.14 s)
1000000 of 1000000 tuples (100%) done (elapsed 1.37 s, remaining 0.00 s)
vacuuming...
creating primary keys...
done.

データの準備ができたら、次はベンチマークを実行します。

$ 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 = 2.408 ms
tps = 4152.303167 (including connections establishing)
tps = 4159.985652 (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 |           96.00
 pgbench_history  |           99.00
 pgbench_tellers  |           99.00
 pgbench_branches |           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  |           94.00
 pgbench_branches | pgbench_branches_pkey |           99.00
 pgbench_accounts | pgbench_accounts_pkey |           99.00
(3 rows)

インストールするマイナーバージョンを指定する場合

以下のコマンドを実行すると、以下のようにインストールできる全てのバージョンが表示されます。
ここから必要なバージョンを探してインストールすればよいです。

# yum --showduplicates search postgresql12-server
~省略~
postgresql12-server-12.0-1PGDG.rhel7.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql12-server-12.1-1PGDG.rhel7.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql12-server-12.1-2PGDG.rhel7.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql12-server-12.2-1PGDG.rhel7.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql12-server-12.2-2PGDG.rhel7.x86_64 : The programs needed to create and run a PostgreSQL server
postgresql12-server-12.3-1PGDG.rhel7.x86_64 : The programs needed to create and run a PostgreSQL server

PostgreSQL 12.3以降の場合

12.3からpostgresXX-develをインストールするのにLLVM関連のライブラリが必要となりました。

# yum -y install postgresql12-devel
~省略~
Error: Package: postgresql12-devel-12.3-1PGDG.rhel7.x86_64 (pgdg12)
           Requires: llvm-toolset-7-clang >= 4.0.1
Error: Package: postgresql12-devel-12.3-1PGDG.rhel7.x86_64 (pgdg12)
           Requires: llvm5.0-devel >= 5.0

EPEL、SCLのリポジトリを追加すれば解消するそうです。

# yum -y install epel-release centos-release-scl

参考

19
23
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
19
23