目的
Postgreでのデータベースサーバー構築を行えるようになる
・Postgreインストール
・ユーザー作成
Postgreのインストール
⭐AmazonLinuxだとPostgreのリポジトリが用意されているのでインストールコマンドだけでおk
RHELだとリポジトリ追加が必要
yum -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
Postgreインストール
yum install -y postgresql15-server
初期化
インストール後は初期化が必要なので下記コマンドで初期化
postgresql-setup initdb
パスワード変更
Postgreをインストールする過程でDB管理用ユーザー『postgres』が自動で生成される
cat /etc/passwd | grep postgres
このユーザーはOS側のパスワードが設定されていないため、手動設定する
passwd postgres
Changing password for user postgres.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
postgresqlのサービス起動
systemctl start postgresql
systemctl enable postgresql
ユーザー関連設定
postgresに変更
sudo su - postgres
### postgresにログイン
```bash
psql
ユーザー一覧表示
\du
ユーザー作成
create userコマンドでユーザー作成
CREATE USER myuser WITH PASSWORD 'securepass123';
\du
ロール操作
既存のユーザーへのロール操作はalter role
コマンド
ALTER ROLE myuser WITH CREATEDB CREATEROLE;
\du
特定ユーザーのログインを禁止する時
ALTER ROLE myuser NOLOGIN;
認証方式変更
peer認証およびident認証ではOSユーザーとDBユーザー名が一致していなければ認証は成功しない。
pg_hba.conf
にpostgresqlの認証設定が記載
pg_hba.conf
の場所は下記コマンドで確認可能
SHOW hba_file;
cat /var/lib/pgsql/data/pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 ident
# 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
peer認証とident認証をscram-sha-256認証に書き換えてサービス再起動
sed -i.backup -e 's/peer/scram-sha-256/g' -e 's/ident/scram-sha-256/g' /var/lib/pgsql/data/pg_hba.conf
また、postgresユーザーだけはpeer認証でログインできるように固定する
vim pg_hba.conf
local all postgres peer
パスワード方式変更
postgreではpg_authidテーブルにユーザーのパスワード情報が保持されている
SELECT rolname, rolpassword FROM pg_authid;
rolname | rolpassword
---------------------------+---------------------------------------------------------------------------------------------------------------------------------------
postgres |
pg_database_owner |
pg_read_all_data |
pg_write_all_data |
pg_monitor |
pg_read_all_settings |
pg_read_all_stats |
pg_stat_scan_tables |
pg_read_server_files |
pg_write_server_files |
pg_execute_server_program |
pg_signal_backend |
pg_checkpoint |
myuser | SCRAM-SHA-256$4096:gZyJL33MaohBR9YswtTf1g==$IovFYtPfJUcP/ZK+rM3hSJUcVDmYAnyC7JJc5mQFOHs=:99QoQdqx9ONmlzmvGtkVIEpTDUCaAz8v8x0IofFRI6o=
(14 rows)
全体でのパスワード方式をscram-sha-256に変更
ALTER SYSTEM SET password_encryption = 'scram-sha-256';
パスワード変更
ALTER USER myuser WITH PASSWORD 'newpassword';
ログイン
作成したmyuserでpostgresqlにログインする
\q #ログアウト
psql -U myuser -d postgres
スーパーユーザーだとプロンプト名に『DB名=#』
通常ユーザーだと『DB名=>』