事象
今Flaskの処理で他サーバーのAPIを叩くコードを書きました。
Flaskの組み込みサーバーはでちゃんと動作するのですが、これをGunicornで実行するとHTTPリクエストを投げた時点でスタックしてしまいます。なぜでしょうか?
再現用のコードは以下です。(簡略化のためにlocalhostの別パスに対してHTTPリクエストを投げるように変更しています。)
python
1from flask import Flask, request, Response 2import os 3 4app = Flask(__name__) 5 6@app.route("/healthz") 7def healthz(): 8 return Response(response="OK", status=200) 9 10@app.route("/test") 11def test(): 12 os.system("curl -I http://127.0.0.1:8080/healthz") # uWSGIやGunicornで実行するとここでスタックする。curlではなくwgetを使ってみたりrequestsモジュールを使っても同様にスタックする 13 return Response(response="OK", status=200) 14 15if __name__ == "__main__": 16 app.run(host="0.0.0.0", port=8080, debug=True)
再現コードの実行方法
うまくいくパターン
以下のようにFlaskの組み込みサーバーで実行するとうまくいきます。
shell
1$ docker run -d -v $PWD:/app -w /app --entrypoint /bin/sh python:3.9 -c "pip install flask; python testfile.py" 2$ curl http://[コンテナのIP]/test 3OK
スタックするパターン
GunicornやuWSGIでこのコードを実行するとHTTPリクエストを投げる時点でスタックします。
shell
1$ docker run -d -v $PWD:/app -w /app --entrypoint /bin/sh python:3.9 -c "pip install flask gunicorn; gunicorn testfile:app" 2$ curl http://[コンテナのIP]/test 3
dockerのログはこのようになります。curlコマンド自体は実行されているようですが応答がなく、30秒後にGunicornのタイムアウトでkillされます。
[2022-11-07 09:22:37 +0000] [17] [INFO] Starting gunicorn 20.1.0 [2022-11-07 09:22:37 +0000] [17] [INFO] Listening at: http://0.0.0.0:8080 (17) [2022-11-07 09:22:37 +0000] [17] [INFO] Using worker: sync [2022-11-07 09:22:37 +0000] [18] [INFO] Booting worker with pid: 18 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- 0:00:30 --:--:-- 0 [2022-11-07 09:23:27 +0000] [17] [CRITICAL] WORKER TIMEOUT (pid:18) [2022-11-07 09:23:28 +0000] [17] [WARNING] Worker with pid 18 was terminated due to signal 9
uWSGIで実行しても同様です。
shell
1$ docker run -d -v $PWD:/app -w /app --entrypoint /bin/sh python:3.9 -c "pip install flask uwsgi; uwsgi --http :8080 --wsgi-file testfile.py --callable app" 2$ curl http://[コンテナのIP]/test 3
バージョン
Python 3.9 (docker)
Flask 2.2.2
gunicorn 20.1.0

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/11/07 12:20
2022/11/07 12:24