サイトロゴ

FlaskアプリケーションをGunicornのWSGIサーバーで運用する方法|macOS

著者画像
Toshihiko Arai

はじめに

以前にPythonのFlaskでRESTなアプリケーションを動かしました。しかし、Flaskの app.run でサーバーを動かすと動作が安定しません。そこで、 Gunicorn を使ったサーバー運用を導入してみました。Gunicornは「Python WSGI HTTP Server for UNIX」です。ここではGunicornのセットアップと起動方法を解説いたします。

開発環境

ここではmacOS上でGunicornを動かす方法を解説いたします。UbuntuなどのLinuxでも設定はほとんど同じです。

Gunicornのインストール

$ pip install gunicorn

アプリケーションの作成

仮に test_gunicorn.py という名前でアプリケーションを作成します。

def app(environ, start_response):
    data = b"Hello, World!\n"
    start_response("200 OK", [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(data)))
    ])
    return iter([data])

Gunicornでアプリケーションサーバーの立ち上げ

Gunicornを使って先ほどのアプリケーションサーバーを立ち上げます。-w はワーカースレッドの数です。

$ gunicorn -w 4 test_gunicorn:app
[2022-12-19 23:06:15 +0900] [43249] [INFO] Starting gunicorn 20.1.0
[2022-12-19 23:06:15 +0900] [43249] [INFO] Listening at: http://127.0.0.1:8000 (43249)
[2022-12-19 23:06:15 +0900] [43249] [INFO] Using worker: sync
[2022-12-19 23:06:15 +0900] [43250] [INFO] Booting worker with pid: 43250
[2022-12-19 23:06:15 +0900] [43251] [INFO] Booting worker with pid: 43251
[2022-12-19 23:06:15 +0900] [43252] [INFO] Booting worker with pid: 43252
[2022-12-19 23:06:15 +0900] [43253] [INFO] Booting worker with pid: 43253

サーバーへリクエストテスト

curlを使ってサーバーへリクエストしてみます。「Hello, World!」の文字列が返ってきたら、サーバーテストの成功です。

$ curl 127.0.0.1:8000        
Hello, World!

Port設定などconfigファイル作成

Gunicornではconfigファイル読み込んで起動することも可能です。そうすることでコマンドオプションを省略できます。次はGunicornのconfigファイルの記述例です。

#
#
wsgi_app = 'server:app'
chdir = '/Users/xxxx/Projects/Sites/iot-dev'
daemon = False
bind = '0.0.0.0:9000'
workers = 2

実行

先ほどの設定ファイルをGunicornで読み込んで起動するには、次のように実行します。

$ gunicorn --config settings.py
[2022-12-19 23:37:56 +0900] [43495] [INFO] Starting gunicorn 20.1.0
[2022-12-19 23:37:56 +0900] [43495] [INFO] Listening at: http://0.0.0.0:9000 (43495)
[2022-12-19 23:37:56 +0900] [43495] [INFO] Using worker: sync
[2022-12-19 23:37:56 +0900] [43496] [INFO] Booting worker with pid: 43496
[2022-12-19 23:37:56 +0900] [43497] [INFO] Booting worker with pid: 43497

関連記事