今回はCentOS 7上にPostgreSQLをインストールする方法を紹介します。yumでのインストールはコマンド一発で終了してしまうので、ソースからのインストール方法と基本的な設定方法を説明します。
この記事の環境
OS、ミドルウェア | バージョン等 |
---|---|
CentOS | 7.2 |
PostgreSQL | 7.0 |
PostgreSQLインストールディレクトリ | /usr/local/pkg/postgresql-9.6.1 |
PostgreSQLデータディレクトリ | /data/pgsql |
事前準備
依存ライブラリのインストール
PostgreSQLのインストールを行うには、gcc-c++、readline-devel、zlib-develが必要になるので、yumでインストールします。
1 2 |
$ sudo yum -y install gcc-c++ readline-devel zlib-devel $ |
ユーザーおよびインストールディレクトリの作成
インストールおよび動作させるユーザーを作成します。ここで作成したユーザーで、PostgreSQLのインストールと、PostgreSQLの実行ユーザーとして使用します。
1 2 3 4 5 6 7 |
$ sudo useradd postgres $ sudo passwd postgres ユーザー postgres のパスワードを変更。 新しいパスワード: (パスワードを入力) 新しいパスワードを再入力してください: (もう一度同じパスワードを入力) passwd: すべての認証トークンが正しく更新できました。 $ |
先程作成したユーザーでPostgreSQLをインストールするために、予めインストールディレクトリを作成します。
この操作を行うことで、rootユーザー以外でもホームディレクトリ以外の指定したディレクトリにインストールすることができます。
1 2 3 |
$ sudo mkdir /usr/local/pkg/postgresql-9.6.1 $ sudo chown postgres: /usr/local/pkg/postgresql-9.6.1 $ |
インストールおよび初期設定
インストール
PostgreSQLのインストールを行います。日本PostgreSQLユーザー会のページからソースファイルをダウンロードしてインストールを行います。
ソースファイルのURLは以下の方法で取得できます。
-
日本PostgreSQLユーザー会のページ上部にあるダウンロードリンクをクリックします。
-
ダウンロードページにあるsourceのURLをクリックします。
-
PostgreSQL公式サイト(英語)のFile Browserページへ遷移しますので、インストールしたいバージョン(今回はv9.6.1)をクリックします。
-
PostgreSQL公式サイトで用意しているファイルの一覧が表示されますので、扱いやすいファイルのURLをコピーしてください。今回はtar.gzファイルを使用します。
1 2 3 4 5 6 |
$ cd /usr/local/src $ sudo curl -OL https://ftp.postgresql.org/pub/source/v9.6.1/postgresql-9.6.1.tar.gz % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 24.0M 100 24.0M 0 0 412k 0 0:00:59 0:00:59 --:--:-- 1526k $ |
ダウンロードできたら、解答してコンパイルおよびインストールを行います。
ソースコードからインストールする場合は、インストール先はすべて一箇所に纏めておいたほうがバージョンアップ等が行いやすいため、configureオプションは–prefixのみ指定します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
$ sudo tar zxf postgresql-9.6.1.tar.gz $ sudo chown -R postgres: postgresql-9.6.1 $ cd postgresql-9.6.1 $ sudo -u postgres ./configure --prefix=/usr/local/pkg/postgresql-9.6.1 checking build system type... x86_64-pc-linux-gnu checking host system type... x86_64-pc-linux-gnu checking which template to use... linux checking whether to build with 64-bit integer date/time support... yes checking whether NLS is wanted... no checking for default port number... 5432 ~省略~ config.status: linking src/backend/port/sysv_sema.c to src/backend/port/pg_sema.c config.status: linking src/backend/port/sysv_shmem.c to src/backend/port/pg_shmem.c config.status: linking src/backend/port/dynloader/linux.h to src/include/dynloader.h config.status: linking src/include/port/linux.h to src/include/pg_config_os.h config.status: linking src/makefiles/Makefile.linux to src/Makefile.port $ $ sudo -u postgres make make -C src all make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src' に入ります make -C common all make[2]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src/common' に入ります make -C ../backend submake-errcodes make[3]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src/backend' に入ります prereqdir=`cd 'utils/' >/dev/null && pwd` && \ ~省略~ make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src' から出ます make -C config all make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/config' に入ります make[1]: `all' に対して行うべき事はありません. make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/config' から出ます All of PostgreSQL successfully made. Ready to install. $ $ sudo -u postgres make install make -C src install make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src' に入ります make -C common install make[2]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src/common' に入ります make -C ../backend submake-errcodes make[3]: ディレクトリ `/usr/local/src/postgresql-9.6.1/src/backend' に入ります make[3]: `submake-errcodes' に対して行うべき事はありません. ~省略~ make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/config' に入ります /bin/mkdir -p '/usr/local/pkg/postgresql-9.6.1/lib/pgxs/config' /bin/install -c -m 755 ./install-sh '/usr/local/pkg/postgresql-9.6.1/lib/pgxs/config/install-sh' /bin/install -c -m 755 ./missing '/usr/local/pkg/postgresql-9.6.1/lib/pgxs/config/missing' make[1]: ディレクトリ `/usr/local/src/postgresql-9.6.1/config' から出ます PostgreSQL installation complete. $ |
以上でインストール自体は終了ですが、後々のバージョンアップを行った際の手間を削減するためにシンボリックリンクを作成します。
1 |
$ sudo ln -s /usr/local/pkg/postgresql-9.6.1 /usr/local/pgsql |
データベースの初期化
PostgreSQLのデータベースの保存領域を作成するために、データベースの初期化を行います。
まずはデータベースの保存領域であるデータディレクトリを作成します。ここもPostgreSQL実行ユーザーでファイルが作成されますので、上で作成したユーザーの権限にしておきます。
1 2 3 |
$ sudo mkdir /data/pgsql $ sudo chown postgres: /data/pgsql $ |
初期化を行うにはinitdbコマンドを使用します。initdbコマンドを使用する場合は、rootユーザーではできませんので注意してください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
$ su - postgres $ /usr/local/pgsql/bin/initdb -D /data/pgsql --no-locale --encoding=UTF-8 The files belonging to this database system will be owned by user "postgres". This user must also own the server process. The database cluster will be initialized with locale "C". The default text search configuration will be set to "english". Data page checksums are disabled. fixing permissions on existing directory /data/pgsql ... ok creating subdirectories ... ok selecting default max_connections ... 100 selecting default shared_buffers ... 128MB selecting dynamic shared memory implementation ... posix creating configuration files ... ok running bootstrap script ... ok performing post-bootstrap initialization ... ok syncing data to disk ... ok WARNING: enabling "trust" authentication for local connections You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb. Success. You can now start the database server using: /usr/local/pgsql/bin/pg_ctl -D /data/pgsql -l logfile start $ |
これでデータベースの初期化が完了しました。initdbコマンドを実行すると、作成したデータディレクトリのアクセス権が700に変わっているので確認してください。このディレクトリにはPostgreSQLの設定ファイルが保存されており、第三者が操作できるようになっている場合は情報を抜き出したり、データを削除したりすることができてしまいますので十分に注意してください。
1 2 3 4 |
$ ls -l /data/ 合計 4 drwx------ 19 postgres postgres 4096 12月 15 17:03 pgsql $ |
この後に説明する起動スクリプトの設定変更を行わないようにするために、データディレクトリのシンボリックリンクを作っておきます。
1 2 |
$ ln -s /data/pgsql /usr/local/pgsql/data $ |
自動起動設定
PostgreSQLをサービスとして登録します。
起動スクリプトは、ダウンロードしたソースファイルの中にありますのでそれを流用します。
1 2 |
$ sudo cp /usr/local/src/postgresql-9.6.1/contrib/start-scripts/linux /etc/init.d/postgresql $ |
もし、複数のPostgreSQLをインストールしたり、データディレクトリを複数持たせたりする場合は、起動スクリプトのprefixやPGDATAを修正する必要があります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#! /bin/sh # chkconfig: 2345 98 02 # description: PostgreSQL RDBMS # This is an example of a start/stop script for SysV-style init, such # as is used on Linux systems. You should edit some of the variables # and maybe the 'echo' commands. # # Place this file at /etc/init.d/postgresql (or # /etc/rc.d/init.d/postgresql) and make symlinks to # /etc/rc.d/rc0.d/K02postgresql # /etc/rc.d/rc1.d/K02postgresql # /etc/rc.d/rc2.d/K02postgresql # /etc/rc.d/rc3.d/S98postgresql # /etc/rc.d/rc4.d/S98postgresql # /etc/rc.d/rc5.d/S98postgresql # Or, if you have chkconfig, simply: # chkconfig --add postgresql # # Proper init scripts on Linux systems normally require setting lock # and pid files under /var/run as well as reacting to network # settings, so you should treat this with care. # Original author: Ryan Kirkpatrick <pgsql@rkirkpat.net> # contrib/start-scripts/linux ## EDIT FROM HERE # Installation prefix prefix=/usr/local/pgsql # Data directory PGDATA="/usr/local/pgsql/data" |
起動スクリプトの準備ができたら、実行権限を与えてPostgreSQLを起動します。
1 2 3 4 |
$ sudo chmod 755 /etc/init.d/postgresql $ sudo systemctl enable postgresql $ sudo systemctl start postgresql $ |
ユーザー設定
PostgreSQLを操作するユーザーの設定を行います。
postgresユーザーのパスワード変更
initdbを実行するとデフォルトでpostgresというスーパーユーザーがデータベース上に作成されます。CentOS上に作成したpostgresユーザーとは別物ですので注意してください。
まずはデータベース上のpostgresユーザーのパスワードを変更します。インストール直後はパスワードが無しの状態になっていますので、必ず設定するようにしてください。
1 2 3 4 5 6 7 8 9 10 |
$ su - postgres $ /usr/local/pgsql/bin/psql -U postgres psql (9.6.1) Type "help" for help. postgres=# ALTER ROLE postgres WITH PASSWORD '(パスワード)'; ALTER ROLE postgres=# postgres=# \q $ |
操作ユーザーの作成
次に、データベースを操作するユーザーを作成します。postgresユーザーはスーパーユーザーであり、このユーザーでも操作することについて何の問題もありませんが、逆に何でもできてしまうため誤ってデータやデータベースを削除してしまったり、悪意のあるユーザーに乗っ取られた場合には被害が大きくなってしまいます。よって、スーパーユーザーよりも権限の低いユーザーを使用して操作を行います。
ユーザーの作成方法は2種類あります。createuserというシェル(shell)コマンドを使用するか、SQLのCREATE USERおよびALTER ROLEを使用するかになります。
シェルコマンドの場合(この操作もrootユーザーではできませんので注意してください。)
1 2 3 4 5 |
$ su - postgres $ /usr/local/pgsql/bin/createuser -P (ユーザー名) Enter password for new role: (パスワードを入力) Enter it again: (再度パスワードを入力) $ |
SQLの場合
1 2 3 4 5 |
postgres=# CREATE USER (ユーザー名); CREATE ROLE postgres=# ALTER ROLE (ユーザー名) WITH PASSWORD '(パスワード)'; postgres=# \q $ |
データベースの作成およびユーザーの所有権の紐付け
データベースの初期化と、ユーザーの作成ができたらデータベースを作成します。
データベースの作成
データベースの作成方法は2種類あります。createdbというシェル(shell)コマンドを使用するか、SQLのCREATE DATABASEを使用するかになります。
シェルコマンドの場合
1 2 3 |
$ su - postgres $ /usr/local/pgsql/bin/createdb -U postgres -E UTF-8 (データベース名) $ |
SQLの場合
1 2 3 4 |
postgres=# CREATE DATABASE (データベース名); CREATE DATABASE postgres=# \q $ |
データベースとユーザーの紐付け
データベースが作成できたら、先程作成したユーザーにこのデータベースの操作権限を与えます。今回与える権限は、先程作成したデータベースに対しての全権限を与えます。
1 2 3 4 |
postgres=# GRANT ALL PRIVILEGES ON DATABASE (データベース名) TO (ユーザー名); GRANT postgres=# \q $ |
アクセス制限
外部接続制限
ユーザーとデータベースの作成が完了したら、そのデータベースへのアクセス制限を設定します。デフォルトのままだと、外部(このマシン以外)からの接続はすべて拒否しており、内部(このマシン)からデータベースにアクセスするとパスワード認証無しで操作することができてしまいます。
JavaやPHPなどからデータベースへ接続する際にもこの設定がされていないと接続できない場合があります。
外部からのアクセスを限定して許可する方法です。データディレクトリにあるpostgresql.confおよびpg_hba.confというファイルで管理していますので、そのファイルを修正します。
1 |
$ sudo vi /usr/local/pgsql/data/postgresql.conf |
このファイルでそもそも外部からの接続を許可するかどうかを設定しています。
lieten_addressesの項目が、localhostの場合は外部からの接続はできず、*(アスタリスク)にすることで外部からの接続が許可されます。デフォルトはlocalhostになっています。
53 54 55 56 57 58 59 60 61 62 63 64 65 |
#------------------------------------------------------------------------------ # CONNECTIONS AND AUTHENTICATION #------------------------------------------------------------------------------ # - Connection Settings - #listen_addresses = 'localhost' # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for all # (change requires restart) listen_addresses = '*' #port = 5432 # (change requires restart) max_connections = 100 # (change requires restart) |
1 |
$ sudo vi /usr/local/pgsql/data/pg_hba.conf |
このファイルの書式はこのファイル内に書いてありますが、外部からのアクセスを制御しているのはADDRESSという部分です。
このADDRESSという部分で許可するネットワーク範囲を設定します。
以下のサンプルでは、ローカルホスト(このマシン)と、192.168.1.0~192.168.1.255までのIPを持つマシンからの接続を許可するようになっています。
81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust host all all 192.168.1.0/24 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres trust #host replication postgres 127.0.0.1/32 trust #host replication postgres ::1/128 trust |
データベース接続認証
データベースへ接続する際にデフォルトの場合はユーザー名とデータベースを入力しただけでログインできてしまいます。セキュリティを考慮してパスワードなどの認証を行うようにします。
データベースの認証についてはMETHODという部分で制御をしています。
METHODに指定できる値はいくつかあります。
- trust
- 認証なし。
- md5
- パスワードをmd5でハッシュした形で保存し認証します。
- password
- パスワードを平文で保存し認証します。
- ident
- OSのユーザーと一致しているかどうかで認証します。OS上とデータベース上で同じユーザー名のユーザーが存在する必要があります。
以下の例ではローカルマシン上ではOSのユーザーと同じユーザーであれば認証が承認され、それ以外(ローカルマシン上でホストを指定した場合も含む)の場合は、md5ハッシュを使用したパスワード認証が行われます。
81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all ident # IPv4 local connections: host all all 127.0.0.1/32 md5 host all all 192.168.1.0/24 md5 # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres trust #host replication postgres 127.0.0.1/32 trust #host replication postgres ::1/128 trust |
作成したユーザーでデータベースを操作する
以上の操作を行うことで、データベースとユーザーの組み合わせで操作することができるようになります。
データベース名 | sample_db |
ユーザー名 | sample |
テーブル名 | tbl_sample |
以下のようなテーブル(sample)を作成します。
カラム名 | 型 | 制約 |
---|---|---|
id | integer | primary key, not null |
name | text | not null |
job | text |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
sample_db=> CREATE TABLE tbl_sample (id integer primary key, name text not null, job text); CREATE TABLE sample_db=> \d tbl_sample Table "public.tbl_sample" Column | Type | Modifiers --------+---------+----------- id | integer | not null name | text | not null job | text | Indexes: "tbl_sample_pkey" PRIMARY KEY, btree (id) sample_db=> |
以上で、CentOS 7上にPostgreSQL9系のインストールおよび初期設定は完了です。