Flask + uWSGI + Nginx架設記錄

我有一支用Python開發的http api程式,是以http.server的module啟動service,但是這僅適合測試環境使用。

後來我把Python改以Flask開發,但是Flask預帶的Web Service也不被建議用在正式環境上。

所以最後我用Flask + uWSGI + Nginx來完成正式環境的架設,記錄一下以免之後忘記了。

安裝Flask、uWSGI、Nginx程式,我的作業系統是ubuntu

# apt install nginx
# pip3 install Flask
# pip3 install uwsgi

我的測試Flash程式,檔名server.py,內容如下:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def test():
    return "相思樹下數相思,怨君不知相思苦"
if __name__ == '__main__':
	app.run()

啟動flask服務,利用curl http://127.0.0.1:5000來看看是否有傳回「相思樹下數相思,怨君不知相思苦」

# python server.py


uWGI可以使用三種協定設定,而nginx則必需配合uWGI的協定來配置

1、socket協定

------------------

uWSGI設定,新增一個配置檔,如uwsgi_test.ini

[uwsgi]
module			= server:app
chdir			= /test_flask
master			= true
processes		= 3
socket			= /var/run/test_uwsgi.sock
die-on-term		= true
chmod-socket	= 666
logto			= /var/log/uwsgi_test.log

moule是設定flask的檔案(不用加.py)及入口程序名,以測試檔server_flask.py而言是指app

chdir是flask程式的路徑

processes是指定uWGI要啟用多少個process

socket是設定scoket的檔案位置,nginx與uWGI依靠這個檔案相互搭起

chmod設定權限,我有試過設定660,結果造成nginx無法讀取socket檔案

logto是設定log的目錄

nginx設定,在/etc/nginx/sites-available內新增配置檔,如webtest.conf

server {
    listen      80;
    charset     utf-8;

    location / {
        try_files $uri @app;
    }
    location @app {
        include     uwsgi_params;
        uwsgi_pass  unix:/var/run/uwsgi_server.sock;
    }
    location /test {
        default_type "text/html";
        alias /html/test01.html;
    }
	location /js {
	    alias /html/js;
	}
}   


2、http協定

-------------------------

uWSGI 配置:

[uwsgi]
wsgi-file = /test_flask/server.py
callable = app
http= :8000
processes = 3
threads = 2
master = true
chmod-socket = 660
vacuum = true
die-on-term = true


wsgi-file是flask的完整檔名



Nginx 配置:

server{
    listen  80;
    location /{
        proxy_pass  http://127.0.0.1:8000;
    }
}


3、uwsgi協定

--------------

uWSGI 配置

[uwsgi]
wsgi-file = server.py
callable = app
socket = :8000
processes = 4
threads = 2
master = true
chmod-socket = 660
vacuum = true
die-on-term = true


Nginx 配置

server{
    listen  80;
    location /{
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:8000;
    }
}


啟動uWSGI、nginx:

# uwsgi test.py
# nginx


利用curl http://127.0.0.1來看看是否成功傳回「相思樹下數相思,怨君不知相思苦」