45
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

flask を uWSGI と Nginx でデプロイする

Last updated at Posted at 2017-07-11

参考にしたページ
How To Serve Flask Applications with uWSGI and Nginx on Ubuntu 16.04

Google Colud の "Debian GNU/Linux 9 (stretch)" でデプロイしました。

実行した結果

gcloud_jul11.png

前提となるソフトのインストール

sudo apt install nginx-full
sudo apt install python3-pip python3-dev
sudo apt install virtualenv

python を、python3 にする

sudo rm /usr/bin/python
sudo ln -s /usr/bin/python3 /usr/bin/python

python のバージョンの確認

python --version

virtualenv の作成

mkdir ~/myproject
cd ~/myproject
virtualenv -p python3 myprojectenv
source myprojectenv/bin/activate

この時点での画面の表示

myproject_jul1101.png

pip install uwsgi flask

flask のプログラムを作成します。

myproject.py
# -*- coding: utf-8 -*-
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    str_out = "<h1 style='color:blue'>Hello There!</h1>"
    str_out += "こんにちは。<p />"
    str_out += "Jul/11/2017<br />"
    str_out += "AM 08:54<br />"
    return str_out

if __name__ == "__main__":
    app.run(host='0.0.0.0')

プログラムが正常に動くか確認

python myproject.py

クライアントで確認

curl http://localhost:5000

uwsgi を使う用意

wsgi.py
# -*- coding: utf-8 -*-
from myproject import app

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

uwsgi を動かす

uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:app

クライアントで確認

curl http://localhost:5000

virtualenv から出る

deactivate

systemd の用意

myproject.ini
[uwsgi]
module = wsgi:app

master = true
processes = 5

socket = myproject.sock
chmod-socket = 660
vacuum = true

die-on-term = true
/etc/systemd/system/myproject.service
[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=uchida
Group=www-data
WorkingDirectory=/home/uchida/myproject
Environment="PATH=/home/uchida/myproject/myprojectenv/bin"
ExecStart=/home/uchida/myproject/myprojectenv/bin/uwsgi --ini myproject.ini

[Install]
WantedBy=multi-user.target

サービスの起動

sudo systemctl start myproject
sudo systemctl enable myproject

Nginx の設定

/etc/nginx/sites-available/myproject
server {
    listen 80;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/uchida/myproject/myproject.sock;
    }
}
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
sudo rm -f /etc/nginx/sites-enabled/default

Nginx の設定が正しいか確認

sudo nginx -t

Nginx の再起動

sudo systemctl restart nginx
45
54
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
45
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?