Flask nginx uWSGI

超簡単ubuntu18.04 + Flask + uWSGI + NginxでWebサーバー

September 16, 2019

#ubuntu #Flask #nginx #uWSGI #python #Webサーバー

ubuntu18.04 + Flask + uWSGI + Nginxで超簡単Webサーバー

1. 環境作成

 $ sudo apt install python3-pip python3-venv python3-dev
 $ mkdir ~/myapp; cd ~/myapp
 $ python3 -m venv env
 $ source env/bin/activate
 (env) $ pip install uwsgi flask

2. ファイル作成

~/myapp/server.py

 from flask import Flask
 app = Flask(__name__)
 @app.route("/")
 def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"
 if __name__ == "__main__":
    app.run(host='0.0.0.0')

~/myapp/wsgi.py

 from server import app

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

~/myapp/server.ini

 [uwsgi]
 module = wsgi:app
 master = true
 processes = 1
 socket = server.sock
 chmod-socket = 666
 vacuum = true
 die-on-term = true
 touch-reload = server.py

/etc/systemd/system/myapp.service

 [Unit]
 Description=uWSGI instance to serve myapp
 After=network.target
 [Service]
 User=<user>
 Group=www-data
 WorkingDirectory=/home/<user>/myapp
 Environment="PATH=/home/<user>/myapp/env/bin"
 ExecStart=/home/<user>/myapp/env/bin/uwsgi --ini server.ini
 [Install]
 WantedBy=multi-user.target

3. サービス起動

 $ sudo systemctl start myapp
 $ sudo systemctl enable myapp # 自動起動
 $ sudo systemctl status myapp # 確認

4. プロキシ設定

/etc/nginx/sites-available/myapp

 server {
    listen 80;
    server_name <domain> www.<domain>;
    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/<user>/myapp/server.sock;
    }
 }
 $ sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled
 $ sudo nginx -t # 確認
 $ sudo systemctl restart nginx # 再起動

以上、超簡単!

SSL対応したい場合は 超簡単ubuntu18.04 + nginx + Let’s Encrypt https初期設定 を見てもらえましたら

5. 参考

How To Serve Flask Applications with uWSGI and Nginx on Ubuntu 18.04