VirtualBox, pyenv, Flask, gunicorn, Apache proxy を使ったデプロイ - AlmaLinux

AlmaLinux の事前準備

このページの記載されている設定の前に、以下の項目の設定が必要です。

  • Linux のパッケージをアップデート
  • pyenv を使った Python のインストール
  • venv(仮想環境)の作成
  • ウェブサーバーのインストール
  • ファイアウォールの設定
  • Python パッケージのインストール(Flask、Waitress、Gunicorn)
  • Flask アプリのダウンロード

上記の設定に関しては、以下のページを参考にしてください。

Apache プロキシサーバーの設定

Apache をプロキシサーバーとして接続する設定をします。/etc/httpd/conf/httpd.confに、以下の内容を追加します。

/etc/httpd/conf/httpd.conf

<VirtualHost *:80>
  ProxyPass / http://localhost:8000/
  ProxyPassReverse / http://localhost:8000/
</VirtualHost>

以下のコマンドを実行して、Gunicornを使って Flask アプリを起動します。

gunicorn -b 127.0.0.1:8000 app:app

Gunicorn をデーモン化する

/etc/systemd/system/gunicorn.service

[Unit]
Description=Gunicorn Flask App
After=network.target

[Service]
Type=simple
User=user
Group=user
WorkingDirectory=/home/user/myapp/flaskapp
Environment="PATH=/home/user/myapp/flaskapp/bin"
ExecStart=/home/user/myapp/flaskapp/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 flaskapp.app:app
Restart=always

[Install]
WantedBy=multi-user.target

ファイルを編集後、systemd を再読み込みするため、以下のコマンドを実行します。

sudo systemctl daemon-reload
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
sudo systemctl status gunicorn

接続できない場合のエラーの確認

エラーが発生するようなら以下のコマンドを実行してエラーの内容を確認します。

journalctl -u gunicorn --no-pager

SELinux のエラーを確認する場合は、以下のコマンドを実行します。

journalctl -xe | grep SELinux