django postgresqlの設定
概要 改正版
centos7にpostgresqlを入れてdjangoを動かす場合を想定している。
djangoでpostgresqlを使うためにdjangoのsettings.pyにpostgresqlのデータベースの諸情報を登録する手続きを取らなければならない。そしてそれは、
- サーバにpostgresqlをインストールする
- データベースクラスターやデータベースを作成する
- postgresqlをpythonで扱うためのモジュールpsycopg2等をインストール
といった下準備が追加的に必要なことを意味する。
postgresqlのデータベースに接続するには3つのステップを踏む。
参考:https://dba.stackexchange.com/questions/180209/postgresql-service-start-failed-on-cento
- postgresqlをインストールする
- データクラスター($PGDATA)を作成する
- サーバーを始動させる
このステップにdjangoでデプロイするための工程を加える。
1.postgresqlをインストールする
外部リポジトリを利用する理由
centos7にはpostgresqlが備え付けられているので、そのまま
sudo yum install postgresql
で、postgresqlをインストールしようと考えることもあろう。
残念ながらこの方法でpostgresqlを使うのは問題がある。問題はpostgresqlのバージョンだ。
試しにcentos7備え付けのpostgresqlをインストールし、バージョンを確認すると以下になる。
$ postgres --version postgres (PostgreSQL) 9.2.24
django2.1からはpostgresql9.4以上を使うことを想定している。
参照:https://docs.djangoproject.com/ja/2.1/releases/2.1/#dropped-support-for-postgresql-9-3
これが備え付けのpostgresqlをインストールする問題点だ。そしてこの問題の避策としてpostgresql公式リポジトリを利用する。下記では公式リポジトリからインストールする方法を記録した。
postgreSQLをインストールする
postgeSQL公式のリポジトリを利用する。
https://yum.postgresql.org/
$ sudo yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
リポジトリにpostgresql11が加えられたかは以下のコマンドで確認する。
# yum info postgresql11-server #結果 Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.cat.net * epel: ftp.jaist.ac.jp * extras: mirrors.cat.net * updates: mirrors.cat.net Available Packages Name : postgresql11-server Arch : x86_64 Version : 11.3 Release : 1PGDG.rhel7 Size : 4.7 M Repo : pgdg11/7/x86_64 Summary : The programs needed to create and run a PostgreSQL server URL : https://www.postgresql.org/ License : PostgreSQL Description : PostgreSQL is an advanced Object-Relational database management system (DBMS). : The postgresql11-server package contains the programs needed to create : and run a PostgreSQL server, which will in turn allow you to create : and maintain PostgreSQL databases. # 上記のように表示されたらdjango用のpostgresqlはインストールされました。
リポジトリをインストール後postgresqlをインストールする。今回はpostgresql11を利用する。
postgresql11-serverのインストールで依存するパッケージもインストールされる。
# yum install postgresql11-server # yum install postgreql-serverにするとcentos7備え付けのpostgresqlをインストールすることになるので気をつけること
そうすると以下のような依存関係にあるものも一緒にインストールされる。
Installed: postgresql11-server.x86_64 0:11.3-1PGDG.rhel7 Dependency Installed: libicu.x86_64 0:50.1.2-17.el7 postgresql11.x86_64 0:11.3-1PGDG.rhel7 postgresql11-libs.x86_64 0:11.3-1PGDG.rhel7
2.データクラスター($PGDATA)を作成する
データクラスターを作成するためにはPostgreSQLの初期化する。初期化すると自動的にデータクラスターを作成される。
参考:https://www.postgresql.jp/document/10/html/creating-cluster.html
初期化するにはinitdbコマンドを入力する必要がある。しかしながらinitdbへのパスが通っていないので以下のようにしてinitdbコマンドを入力する。
# initdbの実行 # /usr/pgsql-11/bin/postgresql-11-setup initdb Initializing database ... OK
インストールするとpostgresユーザが自動的に作成される。このpostgresユーザのパスワードを設定する。パスワードの設定はos(centos7)のユーザ切り替え用のパスワードの設定とpostgresqlに接続するためのパスワードの設定がある。
# osユーザ切り替えのためのパスワード設定 sudo passwd postgres Changing password for user postgres. New password: Retype new password: passwd: all authentication tokens updated successfully.
ちなみにpostgresql11の場合データベースクラスターは以下のパスに作成される。
/var/lib/pgsql/11/data
参考:https://qiita.com/zabutonzabuzabu/items/070a7f833bb321e46b0e
上記の手順について
postgresqlをインストールしたら、まず自分でinitdbコマンドを入力する必要があると考えていた。
しかし以下のドキュメントでは手動でinitdbコマンドを入力する必要はなく、最初のsystemctl start postgresql-11を入力したらデータベースクラスタの初期化(initdb)が行われる、と書いてある。これについてはまだ試していないので試し次第、またこの記事を再編集しようと思う。
https://lets.postgresql.jp/documents/tutorial/centos/2
djangoをデプロイするだけなら説明したように手動でinitdbをする方法で確実に行うことができる。
3.サーバーを始動させる
以下のコマンドで実行する
# systemctl start postgresql-11 # systemctl enable postgresql-11
ポートを開放する
# firewall-cmd --permanent --add-service=postgresql # firewall-cmd --reload # systemctl restart firewalld
ここまででpostgresqlのインストール、初期化、サービスの始動が完了した。
次に
を見ていく。
4.データベースを作成する
データベースを作成する。この時のデータベースはdjangoの仕様に合わせるための設定と自分が作ったプロジェクトに合うための設定(データベース名やユーザー名)を行う。
djangoの仕様に合わせた設定は以下の通りである。
- client_encoding: 'UTF8'
- default_transaction_isolation: 'read committed' by default, or the value set in the connection options (see below)
- timezone: 'UTC' when USE_TZ is True, value of TIME_ZONE otherwise
参照:https://docs.djangoproject.com/ja/2.2/ref/databases/#optimizing-postgresql-s-configuration
下記ではALTER ROLEで設定しているが、postgresql.confでも設定することができるようだ。
# su postgres psql -U postgres
データベースユーザを定める前に、postgresのパスワードを定める。
ALTER ROLE postgres WITH PASSWORD '設定したいpostgresのパスワード';
ここで定めておかないと、pg_hba.confでベーシック認証(md5)に切り替えるのでpostgresユーザーとしてデータベースに接続することができなくなるので注意すること。
データベースを以下のコマンドで作成し、次いでパスワードと一緒にユーザを作成する。
# データベースの作成 CREATE DATABASE [database名] ;
# ユーザを作成する CREATE USER [ユーザ名] WITH PASSWORD '[パスワード]' ;
ALTER ROLE [ユーザ名] SET client_encoding TO 'utf8' ; ALTER ROLE [ユーザ名] SET default_transaction_isolation TO 'read committed'; ALTER ROLE [ユーザ名] SET timezone TO 'Asia/Tokyo'; # このセット内容をデータベースに反映させるコマンドをが以下のもの。 GRANT ALL PRIVILEGES ON DATABASE [database名] TO [ユーザ名]; \q
ALTER ROLE [ユーザ名] SET client_encoding TO 'utf8' ;の関連内容
http://torajirousan.hatenadiary.jp/entry/2019/07/27/042306
5.django settings.pyを編集する
settings.pyの
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', #新たに入力した項目 'NAME': '', # データベース名 'USER': '', # ユーザ名 'PASSWORD': '', # password 'HOST': 'localhost', # DBがあるサーバのIPアドレスやホストを入力。空欄はローカルホスト 'PORT': '5432', # 新たに入力した項目(ポート番号を特に指定しなかったら''でも可) } }
上記のNAMEにdatabase名を、USERにユーザ名を、PASSWORDにパスワードを記述する。
参考:https://docs.djangoproject.com/ja/2.2/intro/tutorial02/#database-setup
つぎにpostgresqlのユーザ認証の設定ファイルを編集する。
vi /var/lib/pgsql/11/data/pg_hba.conf
#認証方法をpeerからmd5に変更 local all all md5
sudo systemctl restart postgresql-11 sudo systemctl status postgresql-11
これでmakemigrationsが通ればオッケイ。
python36 manage.py makemigrations python36 manage.py migrate
参考:https://qiita.com/zabutonzabuzabu/items/070a7f833bb321e46b0e