LoginSignup
0
1

More than 1 year has passed since last update.

FlaskとPostgreSQLの連携

Posted at

前回の記事に引き続き、
HerokuにデプロイしていたFlask,PostgreSQLを使ったアプリケーションを、さくらのVPSに移した際の備忘録です。

今回はCentOSにインストールしたPostgreSQLをFlaskアプリケーションと連携させる手順です。

PostgreSQLを操作する「postgres」ユーザーと「postgres」グループを作成

adduser -U postgres
Enter new password://postgresユーザー用のパスワードを入力
Retype new password://もう一度同じパスワードを入力

/usr/local/に「pgsql」ディレクトリを作成して所有権を「postgres」ユーザーに変更

mkdir /usr/local/pgsql
chown postgres:postgres /usr/local/pgsql

postgresユーザーに切り替えて、/usr/local/pgsqlに移動

su - postgres
cd /usr/local/pgsql

/usr/local/pgsqlにPostgreSQL14.5をダウンロードして解凍

wget https://ftp.postgresql.org/pub/source/v14.5/postgresql-14.5.tar.gz --no-certificate
tar xvfz postgresql-14.5.tar.gz

各バージョンのソース一覧はこちら
https://www.postgresql.org/ftp/source/

コンパイルとインストール

cd postgresql-14.5
./configure --prefix=/usr/local/pgsql
gmake
cd contrib
gmake
cd ..
gmake install
cd contrib
gmake install

psqlのインストール

※ルートユーザーで作業

yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
yum install -y postgresql14-server

PostgreSQLの初期化

※postgresユーザーで作業

su -

/usr/local/pgsql/dataにデータベースクラスタを作成

cd /usr/pgsql-14/bin/
postgresql-14-setup initdb

PostgreSQLの起動

systemctl start postgresql-14.service

PythonアプリケーションからPostgreSQLに接続するためにpostgresql.confを編集

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

//60行目あたり
listen_addresses = '*' 
#listen_addresses = 'localhost'

PostgreSQLを再起動

systemctl restart postgresql-14.service

PostgreSQLが使うポート番号5432を解放

※ルートユーザーで作業

su -
firewall-cmd --permanent --add-port=5432/tcp

firewallを再起動

firewall-cmd --reload

データベースが正しく稼働しているか確認

※postgresユーザーで作業

su - postgres
psql -l

データベース一覧が表示されたら、正しく稼働しています。

0
1
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
0
1