LoginSignup
18
16

More than 3 years have passed since last update.

CentOS 7にPostgreSQL11をインストールする

Last updated at Posted at 2019-05-03

環境

CentOS 7にPostgreSQL11をインストールした際のメモです。

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

手順はほとんど同じですが、PostgreSQL12用は以下のとおりです。

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

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

Complete!

PostgreSQLのインストール

PostgreSQLをインストールします。

# yum -y install postgresql11-server postgresql11-contrib

~省略~
Running transaction
  Installing : postgresql11-libs-11.5-1PGDG.rhel7.x86_64                                                                                             1/6 
  Installing : libicu-50.2-3.el7.x86_64                                                                                                              2/6 
  Installing : postgresql11-11.5-1PGDG.rhel7.x86_64                                                                                                  3/6 
  Installing : libxslt-1.1.28-5.el7.x86_64                                                                                                           4/6 
  Installing : postgresql11-contrib-11.5-1PGDG.rhel7.x86_64                                                                                          5/6 
  Installing : postgresql11-server-11.5-1PGDG.rhel7.x86_64                                                                                           6/6 
  Verifying  : postgresql11-server-11.5-1PGDG.rhel7.x86_64                                                                                           1/6 
  Verifying  : libicu-50.2-3.el7.x86_64                                                                                                              2/6 
  Verifying  : postgresql11-contrib-11.5-1PGDG.rhel7.x86_64                                                                                          3/6 
  Verifying  : postgresql11-libs-11.5-1PGDG.rhel7.x86_64                                                                                             4/6 
  Verifying  : libxslt-1.1.28-5.el7.x86_64                                                                                                           5/6 
  Verifying  : postgresql11-11.5-1PGDG.rhel7.x86_64                                                                                                  6/6 

Installed:
  postgresql11-contrib.x86_64 0:11.5-1PGDG.rhel7                              postgresql11-server.x86_64 0:11.5-1PGDG.rhel7                             

Dependency Installed:
  libicu.x86_64 0:50.2-3.el7    libxslt.x86_64 0:1.1.28-5.el7    postgresql11.x86_64 0:11.5-1PGDG.rhel7    postgresql11-libs.x86_64 0:11.5-1PGDG.rhel7   

Complete!

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

# ls -l /usr/pgsql-11/
total 12
drwxr-xr-x. 2 root root 4096 May  1 03:42 bin
drwxr-xr-x. 3 root root 4096 May  1 03:42 lib
drwxr-xr-x. 7 root root 4096 May  1 03:42 share

PostgreSQLの自動起動

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

# systemctl enable postgresql-11.service

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

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

$ vi /usr/lib/systemd/system/postgresql-11.service

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

$ systemctl daemon-reload

次にデータベースクラスタを作成するために以下のコマンドを実行します。(initdbコマンドでも作成できますが、今回はpostgresql-11-setupを使用しました)

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

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

# cat /data/PG_VERSION 
11

PostgreSQLを起動する

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

# su - postgres

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

# vi /var/lib/pgsql/.pgsql_profile
PATH=/usr/pgsql-11/bin:$PATH
export PATH

PGDATAを修正します。

# vi /var/lib/pgsql/.bash_profile
#PGDATA=/var/lib/pgsql/11/data
PGDATA=/data

# source ~/.bash_profile

PostgreSQLの起動は「pg_ctl start」で行います。

$ pg_ctl start
waiting for server to start....2019-05-01 03:58:27.020 CEST [12912] LOG:  listening on IPv6 address "::1", port 5432
2019-05-01 03:58:27.020 CEST [12912] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2019-05-01 03:58:27.022 CEST [12912] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2019-05-01 03:58:27.025 CEST [12912] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2019-05-01 03:58:27.033 CEST [12912] LOG:  redirecting log output to logging collector process
2019-05-01 03:58:27.033 CEST [12912] HINT:  Future log output will appear in directory "log".
 done
server started

※ "systemctl start postgresql-11"でもOK

データベース確認

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

-bash-4.2$ psql -V
psql (PostgreSQL) 11.2
-bash-4.2$ 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

ユーザとデータベースの作成

ユーザ("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/11/data/postgresql.conf」

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

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

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

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

$ psql
psql (11.5)
Type "help" for help.

postgres=# alter role postgres with password 'postgres';

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

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

$ psql testdb testuser
Password for user testuser: 
psql (11.2)
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/11/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 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...
100000 of 100000 tuples (100%) done (elapsed 0.12 s, remaining 0.00 s)
vacuuming...
creating primary keys...
done.

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

$ pgbench -c 10 -t 1000 testdb
starting vacuum...end.
transaction type: <builtin: TPC-B (sort of)>
scaling factor: 1
query mode: simple
number of clients: 10
number of threads: 1
number of transactions per client: 1000
number of transactions actually processed: 10000/10000
latency average = 7.902 ms
tps = 1265.495967 (including connections establishing)
tps = 1265.842732 (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             |           60.00
 pgbench_accounts |           98.00
 pgbench_history  |           99.00
 pgbench_tellers  |           99.00
 pgbench_branches |           99.00

インデックスのキャッシュヒット率は以下のとおり。

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  |           96.00
 pgbench_branches | pgbench_branches_pkey |           99.00
 pgbench_accounts | pgbench_accounts_pkey |           99.00

参考

18
16
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
18
16