とーますメモ

Ruby on Rails / Goなどの学習メモ

【Python】Flaskの本番環境について調べてみた

Flaskにはbuilt-inサーバがついているので、開発には全く困らないが
公式サイトを見ると以下のように記述があるので、本番環境は別に構築する必要がある。

While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.

by Deployment Options — Flask Documentation (1.1.x)

調べてみたが大体の本番環境構成は以下。

1)Flask + nginx + uWSGI
2)Flask + nginx + Gunicorn
3)Flask + Apache + mod_wsgi

自分の用途はとりあえずそれなりの本番環境が簡単に作れれば良いぐらいの考えなので
Flask + nginx + Gunicornの構成が一番簡単で良さげ。

参照した記事は以下
Which WSGI server should I use? — Django deployment
https://www.airpair.com/python/posts/python-servers
Web Applications & Frameworks — The Hitchhiker's Guide to Python
fcgi vs. gunicorn vs. uWSGI - Peterbe.com
Gunicorn vs uWSGI | What are the differences?

中でも以下の説明がわかりやすくてよかった。

Gunicorn and uWSGI Gunicorn and uWSGI are two different application servers.
Gunicorn 'Green Unicorn' is a Python WSGI HTTP Server for UNIX. It is very simple to configure, compatible with many web frameworks and its fairly speedy. This article by digitalocean shows how to configure gunicorn with nginx.


uWSGI is another option for an application server. uWSGI is a high performance and a powerful WSGI server. There are many configuration options available with uWSGI. This article by digitalocean shows how to configure uWSGI with nginx.


What I use I use Nginx because it is fast , light and I find the configuration to be much easy. Gunicorn is very simple to configure. So I use gunicorn. uWsgi is also used a lot instead of gunicorn.

一番高いパフォーマンスを目指すならuWSGIが良いけど、ただ設定が複雑。
それなりにちゃんと動作し、それなりに速く、設定がシンプルにものを選ぶならGunicorn。
他の記事を見るとWindowsサーバだとApache + mod_wsgiの一択っぽい。

ということで自分は上記の理由から「Flask + nginx + Gunicorn」の構成を選択する。

設定の仕方については以下のサイトを後ほど参考にする
https://medium.com/faun/deploy-flask-app-with-nginx-using-gunicorn-7fda4f50066a
https://martin-thoma.com/flask-gunicorn/

[その他参考]
・Flask + nginx + uWSGIについて
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04
https://medium.com/@smirnov.am/running-flask-in-production-with-docker-1932c88f14d0
https://www.serverlab.ca/tutorials/containers/kubernetes/how-to-run-flask-docker-containers-in-kubernetes/

・Flask + nginx + Gunicornについて
https://www.toptal.com/flask/flask-production-recipes
https://www.linode.com/docs/development/python/flask-and-gunicorn-on-ubuntu/
https://blog.miguelgrinberg.com/post/running-a-flask-application-as-a-service-with-systemd
https://superset.incubator.apache.org/installation.html#a-proper-wsgi-http-server