0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask + uWSGI + Nginxをローカル環境で設定

Posted at

環境

  • Ubuntu 24.04
  • Python 3.8.20
    • Pythonがインストールされている状態
  • nginx-1.26.3
  • 推奨される設定状態
    • sites-availablesites-enabledディレクトリが存在する
    • /etc/nginx/sites-enabled/内の設定ファイルがNginxの設定に組み込まれている

Nginxのインストールや環境設定については下記のページをご覧ください

手順1:仮想環境の構築

適当なディレクトリ内で仮想環境の構築を行います

python3 -m venv venv
source venv/bin/activate
pip install -U pip

手順2:FlaskやuWSGIのインストール

pip install flask uwsgi

手順3:Flaskアプリの作成

仮想環境の構築を行ったディレクトリ内で、Flaskの簡単なアプリを作成します

app.py
from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return 'Hello, uWSGI!'


if __name__ == '__main__':
    app.run()

手順4:uWSGIの設定

uwsgi.ini
[uwsgi]
socket = 127.0.0.1:5000
wsgi-file = /path/to/your/app.py
callable = app
master = true
processes = 4
threads = 2
  • socket = 127.0.0.1:5000
    • uWSGIがリクエストを受け取る ソケット の設定
  • wsgi-file = /path/to/your/app.py
    • uWSGIが実行する FlaskアプリケーションのWSGIファイル を指定
  • callable = app
    • uWSGIがFlaskアプリケーションをロードする際に、wsgi-file で指定したPythonファイル内の app という名前のオブジェクト を呼び出します
  • master = true
    • uWSGIのマスタープロセスの有効化
    • マスタープロセスを使うことで、複数のワーカープロセスを効率的に管理し、プロセスの再起動などが容易になります
  • processes = 4
    • uWSGIが4つのワーカープロセスを起動することを指定
    • これにより、uWSGIはリクエストを並列に処理することができ、複数のリクエストを効率よくさばくことができます
  • threads = 2
    • 各ワーカープロセスが 2つのスレッド を使用することを指定
    • これにより、各ワーカープロセスが複数のスレッドで並列にリクエストを処理できるようになります。ワーカーの数とスレッド数を適切に設定することで、アプリケーションのパフォーマンスを調整できます

手順5:uWSGIの起動

uwsgi --ini uwsgi.ini

手順6:Nginxの設定

/etc/nginx/sites-available/uwsgi_flask
server {
        listen 8080;
        server_name localhost;

        location / {
                # NginxがuWSGIと通信するために必要な設定の読み込み
                include uwsgi_params;
                # uwsgi_passは、Nginxが受け取ったリクエストを uWSGIサーバー(127.0.0.1:5000)に転送する設定
                uwsgi_pass 127.0.0.1:5000;
        }

        # エラーログの記録
        error_log /var/log/nginx/uwsgi_flask_error.log;
        # アクセスログの記録
        access_log /var/log/nginx/uwsgi_flask_access.log;
}

手順7:sites-enabled/にシンボリックリンクを作成

sudo ln -s /etc/nginx/sites-available/uwsgi_flask /etc/nginx/sites-enabled/

手順8:設定の反映

sudo systemctl reload nginx
sudo systemctl restart nginx

http://localhost:8080にアクセスすると、http://localhost:5000に表示されているページの表示ができました。
image.png

まとめ

以上でFlask + uWSGI + Nginxができました

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?