📚

【AWS】【EC2】PostgreSQLをインストールしよう

2025/01/04に公開

AWS で DB を使用する際にはRDSDynamoDBが多いと思います。

ただ、勉強用に使用したり、個人開発などコストがかけられない場合があります。

そこで、今回はEC2 に PostgreSQL をインストールし、初期設定をしていきます

※実行ユーザー:ec2-user

インストール

パッケージを確認する

amazon-linux-extras を確認し、インストールできるバージョンを確認します

(実行コマンド)

amazon-linux-extras list | grep postgresql

(実行結果)

[ec2-user@ip-×××-××-××-×× ~]$ amazon-linux-extras list | grep postgresql
  6  postgresql10             available    [ =10  =stable ]
 41  postgresql11             available    [ =11  =stable ]
 58  postgresql12             available    [ =stable ]
 59  postgresql13             available    [ =stable ]
 63  postgresql14             available    [ =stable ]

→ postgresql10~14 をインストールできます

インストール

今回は、postgresql14をインストールします

また、一緒に追加のパッケージもインストールします

各パッケージに関しては以下の記事をご参考ください

https://torajirousan.hatenadiary.jp/entry/2019/04/24/174843

(実行コマンド)

sudo amazon-linux-extras install -y postgresql14
sudo yum install -y postgresql-server postgresql-devel postgresql-contrib postgresql-docs

(実行結果)

[ec2-user@ip-×××-××-××-×× ~]$ sudo amazon-linux-extras install -y postgresql14
Installing postgresql
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Cleaning repos: amzn2-core amzn2extra-docker amzn2extra-kernel-5.10 amzn2extra-nginx1 amzn2extra-postgresql14 amzn2extra-python3.8
21 metadata files removed
10 sqlite files removed
0 metadata files removed
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core
()
 60  mock2                    available    [ =stable ]
 61  dnsmasq2.85              available    [ =stable ]
 62  kernel-5.15              available    [ =stable ]
 63  postgresql14=latest      enabled      [ =stable ]
 64  firefox                  available    [ =stable ]
 65  lustre                   available    [ =stable ]
[ec2-user@ip-×××-××-××-×× ~]$ sudo yum install -y postgresql-server postgresql-devel postgresql-contrib postgresql-docs
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Package postgresql-devel is obsoleted by libpq-devel, trying to install libpq-devel-14.3-2.amzn2.0.2.x86_64 instead
Resolving Dependencies
--> Running transaction check
---> Package libpq-devel.x86_64 0:14.3-2.amzn2.0.2 will be installed
---> Package postgresql-contrib.x86_64 0:14.3-2.amzn2.0.1 will be installed
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.22)(64bit) for package: postgresql-contrib-14.3-2.amzn2.0.1.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.18)(64bit) for package: postgresql-contrib-14.3-2.amzn2.0.1.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.11)(64bit) for package: postgresql-contrib-14.3-2.amzn2.0.1.x86_64
--> Processing Dependency: libxslt.so.1()(64bit) for package: postgresql-contrib-14.3-2.amzn2.0.1.x86_64
--> Processing Dependency: libossp-uuid.so.16()(64bit) for package: postgresql-contrib-14.3-2.amzn2.0.1.x86_64
---> Package postgresql-docs.x86_64 0:14.3-2.amzn2.0.1 will be installed
---> Package postgresql-server.x86_64 0:14.3-2.amzn2.0.1 will be installed
--> Running transaction check
---> Package libxslt.x86_64 0:1.1.28-6.amzn2 will be installed
---> Package uuid.x86_64 0:1.6.2-26.amzn2.0.1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved
(略)
ependency Installed:
  libxslt.x86_64 0:1.1.28-6.amzn2                                                                        uuid.x86_64 0:1.6.2-26.amzn2.0.1

Complete!

インストールできたか確認

インストールした PostgreSQL のバージョンを確認します

(実行コマンド)

psql -V

(実行結果)

[ec2-user@ip-×××-××-××-×× ~]$ psql -V
psql (PostgreSQL) 14.3

今回は postgresql14 をインストールしたので、14 と表示されれば OK です

初期設定

起動する前に初期化

データベースクラスタ(データベースを格納する領域)の作成など初期化します

具体的には、/var/lib/pgsql/dataに設定ファイルなどが配置されます

(実行コマンド)

sudo postgresql-setup initdb

(実行コマンド)

[ec2-user@ip-×××-××-××-×× ~]$ sudo postgresql-setup initdb
WARNING: using obsoleted argument syntax, try --help
WARNING: arguments transformed to: postgresql-setup --initdb --unit postgresql
 * Initializing database in '/var/lib/pgsql/data'
 * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log

/var/lib/pgsql/initdb_postgresql.logにログがあるそうなので、確認します

(実行コマンド)

sudo cat /var/lib/pgsql/initdb_postgresql.log

(実行結果)

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 "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/pgsql/data ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Asia/Tokyo
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    /usr/bin/pg_ctl -D /var/lib/pgsql/data -l logfile start

エラーは出てなさそう! なので、次に進みます

postgresql を起動&自動起動設定

  1. postgresql を起動します
    sudo systemctl start postgresql
    
  2. 起動したか確認します
    systemctl status postgresql
    
    Active: active (running) となっていることを確認します
  3. 自動起動(サーバーの起動と一緒に起動する)を設定します
    sudo systemctl enable postgresql
    
  4. 自動起動設定を確認します
    systemctl is-enabled postgresql
    
    enabledと表示されれば OK!

(実行結果)

[ec2-user@ip-×××-××-××-×× ~]$ sudo systemctl start postgresql
[ec2-user@ip-×××-××-××-×× ~]$ systemctl status postgresql
�� postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled)
   Active: active (running) since Sun 2022-10-16 18:33:44 JST; 7s ago
  Process: 2001 ExecStartPre=/usr/libexec/postgresql-check-db-dir %N (code=exited, status=0/SUCCESS)
 Main PID: 2003 (postmaster)
   CGroup: /system.slice/postgresql.service
           tq2003 /usr/bin/postmaster -D /var/lib/pgsql/data
           tq2006 postgres: logger
           tq2008 postgres: checkpointer
           tq2009 postgres: background writer
           tq2010 postgres: walwriter
           tq2011 postgres: autovacuum launcher
           tq2012 postgres: stats collector
           mq2013 postgres: logical replication launcher

Oct 16 18:33:44 ip-×××-××-××-××.ap-northeast-1.compute.internal systemd[1]: Starting PostgreSQL database server...
Oct 16 18:33:44 ip-×××-××-××-××.ap-northeast-1.compute.internal postmaster[2003]: 2022-10-16 18:33:44.618 JST [2003] LOG:  redirecting log output to logging collector process
Oct 16 18:33:44 ip-×××-××-××-××.ap-northeast-1.compute.internal postmaster[2003]: 2022-10-16 18:33:44.618 JST [2003] HINT:  Future log output will appear in directory "log".
Oct 16 18:33:44 ip-×××-××-××-××.ap-northeast-1.compute.internal systemd[1]: Started PostgreSQL database server.
[ec2-user@ip-×××-××-××-×× ~]$ sudo systemctl enable postgresql
Created symlink from /etc/systemd/system/multi-user.target.wants/postgresql.service to /usr/lib/systemd/system/postgresql.service.
[ec2-user@ip-×××-××-××-×× ~]$ systemctl is-enabled postgresql
enabled

サーバー内の postgres ユーザーの設定をする

postgresql を install をした際にサーバー内に postgresというユーザーが作成されました。

このユーザーに対して、パスワード と sudoers の設定をします

パスワードを設定する

(実行コマンド)

sudo passwd postgres

→ パスワードを 2 回入力して設定します

(実行結果)

[ec2-user@ip-×××-××-××-×× ~]$ sudo passwd postgres
Changing password for user postgres.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

sudo 権限を付与する

  1. visudo コマンドで対象のファイルを開きます
    sudo visudo -f /etc/sudoers.d/cloud-init
    
  2. 「i」を押して、編集モードにします
  3. 下記を記述します
    postgres ALL = (ALL) ALL
    
  4. 「esc」キーを押して編集モードを抜けます
  5. :wq!」と入力して、ファイルを保存します

これで、postgres ユーザーで sudo コマンドが使用できるようになりました

DB の postgres ユーザーのパスワードを設定する

先ほどとは違い、データベースの postgres ユーザーのパスワードを設定します

  1. postgres ユーザーに切り替えます
    su - postgres
    
    先ほど設定したパスワードを入力します
  2. データベースの postgres ユーザーのパスワードを設定します
    psql -c "ALTER USER postgres PASSWORD '<設定したいパスワード>';"
    

PostgreSQL の設定を変更する

設定ファイルを変更する

※postgres ユーザーのまま実行してください

/var/lib/pgsql/data/postgresql.conf

以下2つのパラメータを確認します

  1. listen_addresses
    • PostgreSQL に接続できる IP アドレスを設定できるパラメータ。
    • すべての IP から受け付ける場合には '*'
    • 複数指定する場合には '<IP①>,<IP②>,...' とカンマ(,)区切りで指定する。
    • 今回は '*' としますが、 セキュリティ的には IP を指定したほうがいいです。**
  2. port
    • PostgreSQL を立ち上げるポート番号を指定しているパラメータ。
    • デフォルトは 5432ですが、セキュリティ的には変更したほうがいい。
    • 今回はデフォルトの 5432 のままにします。

(設定手順)

  1. vim で /var/lib/pgsql/data/postgresql.conf を編集します
    vi /var/lib/pgsql/data/postgresql.conf
    
  2. 「listen_addresses」と検索します→「/listen_addresses」と入力し、Enter キー を押します
  3. 「i」と入力し、INSERT モードにします
  4. listen_addresses=’*’」へ変更します ※適宜、port を含め設定したい値へ変更してください
  5. Esc キーを押し、INSERT モードを終了します
  6. 「:wq!」と入力し、Enter キーを押します

(設定後のファイルを一部抜粋)

#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*'          # 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)
max_connections = 100                   # (change requires restart)
#superuser_reserved_connections = 3     # (change requires restart)
#unix_socket_directories = '/var/run/postgresql, /tmp'  # comma-separated list of directories
                                        # (change requires restart)
#unix_socket_group = ''                 # (change requires restart)
#unix_socket_permissions = 0777         # begin with 0 to use octal notation
                                        # (change requires restart)
#bonjour = off                          # advertise server via Bonjour
                                        # (change requires restart)
#bonjour_name = ''                      # defaults to the computer name
                                        # (change requires restart)

/var/lib/pgsql/data/pg_hba.conf

ローカル(今回の場合 EC2)や他のサーバー、PC など IP アドレスごとに アクセスする際の認証方法を設定します

(設定手順)

  1. vim で /var/lib/pgsql/data/pg_hba.conf を編集します
    vi /var/lib/pgsql/data/pg_hba.conf
    
  2. 「listen_addresses」と検索します→「/listen_addresses」と入力し、Enter キー を押します
  3. 「i」と入力し、INSERT モードにします
  4. ローカルからアクセスする場合の認証方法を peer → md5 へ変更します(下記へ変更)
    # "local" is for Unix domain socket connections only
    #local   all             all                                     peer
    local   all             all                                     md5
    
  5. 外部からアクセスする場合の認証方法を md5 に変更します(下記へ変更)
    # IPv4 local connections:
    #host    all             all             127.0.0.1/32            ident
    host    all             all             0.0.0.0/0           md5
    
  6. Esc キーを押し、INSERT モードを終了します
  7. 「:wq!」と入力し、Enter キーを押します

(設定後のファイルを一部抜粋)

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
#local   all             all                                     peer
local   all             all                                     md5
# IPv4 local connections:
#host    all             all             127.0.0.1/32            ident
host    all             all             0.0.0.0/0           md5
# IPv6 local connections:
host    all             all             ::1/128                 ident
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident
host    replication     all             ::1/128                 ident

PostgreSQL を再起動して、設定を反映させる

(実行コマンド)

sudo systemctl restart postgresql

# reloadでも大丈夫です
# この場合、サービスが停止せず、設定ファイルのみ再読み込みする
sudo systemctl reload postgresql

(実行結果)

-bash-4.2$ sudo systemctl restart postgresql
-bash-4.2$ sudo systemctl status postgresql
�� postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2022-10-16 18:48:37 JST; 7s ago
  Process: 2256 ExecStartPre=/usr/libexec/postgresql-check-db-dir %N (code=exited, status=0/SUCCESS)
 Main PID: 2259 (postmaster)
   CGroup: /system.slice/postgresql.service
           tq2259 /usr/bin/postmaster -D /var/lib/pgsql/data
           tq2262 postgres: logger
           tq2264 postgres: checkpointer
           tq2265 postgres: background writer
           tq2266 postgres: walwriter
           tq2267 postgres: autovacuum launcher
           tq2268 postgres: stats collector
           mq2269 postgres: logical replication launcher

Oct 16 18:48:37 ip-×××-××-××-××.ap-northeast-1.compute.internal systemd[1]: Stopped PostgreSQL database server.
Oct 16 18:48:37 ip-×××-××-××-××.ap-northeast-1.compute.internal systemd[1]: Starting PostgreSQL database server...
Oct 16 18:48:37 ip-×××-××-××-××.ap-northeast-1.compute.internal postmaster[2259]: 2022-10-16 18:48:37.593 JST [2259] LOG:  redirecting log output to logging collector process
Oct 16 18:48:37 ip-×××-××-××-××.ap-northeast-1.compute.internal postmaster[2259]: 2022-10-16 18:48:37.593 JST [2259] HINT:  Future log output will appear in directory "log".
Oct 16 18:48:37 ip-×××-××-××-××.ap-northeast-1.compute.internal systemd[1]: Started PostgreSQL database server.

EC2 のセキュリティグループの設定を変更する

筆者はPostgreSQL をデフォルトの 5432 ポートで起動させているので、 そこへアクセスできるようEC2 のセキュリティグループを設定します

まず、AWS コンソール->EC2->インスタンスとアクセスし、 対象の EC2 を選択し、セキュリティにあるセキュリティグループをクリックします

インバウンドのルールを編集」をクリックします

ルールを追加」をクリックし、タイプを「PostgreSQL」を選択します

今回は、自分の PC からのみアクセスしたいので、ソースに「マイ IP」を選択します

PostgreSQL を立ち上げるポートをデフォルトから変更した場合は、タイプを「カスタム TCP」、ポート範囲を変更後のポート番号にしてください

Postgresql に接続してみる

EC2 内からアクセスしてみる

EC2 内で下記コマンドを実行します ※コマンドの実行ユーザーはなんでも大丈夫です

(実行コマンド)

psql -U postgres

(実行結果)

[ec2-user@ip-×××-××-××-×× ~]$ psql -U postgres
Password for user postgres:
psql (14.3)
Type "help" for help.

postgres=#
postgres=#
postgres=# exit         # exitで抜けます
[ec2-user@ip-×××-××-××-×× ~]$

自分の PC からアクセスしてみる

PowerShell や ターミナル、Ubuntsu など自分の PC からアクセスしてみます

(実行コマンド)

psql -h <EC2のパブリックIP or DNS> -U postgres

# PostgreSQLを起動するポートを変更した場合はポートも指定します
psql -h <EC2のパブリックIP or DNS>:<ポート番号> -U postgres

(実行結果)

root@××:~# psql -h ec2-××-××-×××-×××.ap-northeast-1.compute.amazonaws.com -U postgres
Password for user postgres:
psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1), server 14.3)
Type "help" for help.

postgres=#
postgres=#
postgres=# exit
root@××:~#

以上で、PostgreSQL のインストールと初期設定、アクセスまで完了しました

参考記事

https://zenn.dev/uotohotaru/articles/0730f90dbf7a6d

https://www.dragonarrow.work/articles/157

https://qiita.com/awakia/items/991d4a35aabcdf4c4990

https://blackbird-blog.com/aws-ec2-postgresql1

Discussion