用nginx作通過(guò)內(nèi)置的uwsgi接口反向代理運(yùn)行在uWSGI服務(wù)器上的Flask應(yīng)用,是一種安全高效的架構(gòu)??紤]到完全不管理TCP端口等資源,通過(guò)unix socket file連接nginx和uWSGI是一種理想的方案。但使用socket file必須注意處理nginx訪(fǎng)問(wèn).sock文件權(quán)限的問(wèn)題。主要就是在uWSGI的應(yīng)用配置中使用--chown-socket=nginx:nginx和--chmod-socket=666來(lái)定義.sock文件的所有權(quán)和訪(fǎng)問(wèn)屬性,同時(shí)要注意.sock文件的位置最好放在/tmp或者/usr/local/share這一類(lèi)nginx可以訪(fǎng)問(wèn)的目錄。
本例子將應(yīng)用部署在nginx的/hello二級(jí)目錄下,兩個(gè)應(yīng)用分別通過(guò)http://URL/hello和http://URL/hello/a2訪(fǎng)問(wèn)。以下首先是hello.py程序文件:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def main():
return 'Hello world 你好世界!(對(duì)應(yīng)mount point的根目錄)\n'
@app.route('/a2')
def a2():
return '這是App-2.(對(duì)應(yīng)mount point的子目錄/a2)\n'
注意uWSGI的運(yùn)行配置文件(hello.ini)如下:
[uwsgi]
# 啟用主進(jìn)程
master = true
# 進(jìn)程數(shù)
processes = 1
# 線(xiàn)程數(shù)
threads = 1
# 切換工作目錄。由于影響外部庫(kù)的調(diào)用,應(yīng)該設(shè)定為各外部庫(kù)和uWSGI server編譯
# 安裝的環(huán)境根目錄(默認(rèn)為Anaconda環(huán)境的根目錄)。若在虛擬環(huán)境中編
# 譯安裝了uWSGI,可指定虛擬環(huán)境的根目錄作工作目錄。
chdir = /<hello.py>所在的程序目錄/
# 設(shè)置mount point為將要部署的nginx路徑位置名稱(chēng)(這里是‘/hello’)
# 應(yīng)用則是.py程序的文件名(這里是‘hello’,不含.py后綴)
# app是Flask程序的對(duì)象名(‘a(chǎn)pp=Flask(__name__)’里定義)
mount = /hello=hello:app
# 這個(gè)參數(shù)是由uWSGI管理腳本名稱(chēng)的意思,也就是uWSGI會(huì)根據(jù)nginx訪(fǎng)問(wèn)的目錄和文件名調(diào)用Flask路由相應(yīng)的腳本(即@app.route()修飾的不同函數(shù))
manage-script-name = true
# 直接通過(guò)uWSGI內(nèi)置的http服務(wù)訪(fǎng)問(wèn),端口是9900
http-socket = 127.0.0.1:9900
# uwsgi接口地址及端口。默認(rèn)為本地9999端口,可通過(guò)uwsgi_pass 127.0.0.1:9999;轉(zhuǎn)發(fā)。
uwsgi-socket = 127.0.0.1:9999
# socket接口文件,注意放在一個(gè)nginx有訪(fǎng)問(wèn)權(quán)的目錄
uwsgi-socket = /usr/local/share/hello.sock
# 將socket文件的所有權(quán)分配給nginx的用戶(hù)和組(與nginx.conf中的值對(duì)應(yīng))
chown-socket = nginx:nginx
# 設(shè)置socket文件的讀寫(xiě)權(quán)限
chmod-socket = 666
stats = 127.0.0.1:9191
nginx的配置:
server {
listen 80;
server_name localhost;
location = /hello { rewrite ^ /hello/; }
location /hello { try_files $uri @hello; }
location @hello {
include uwsgi_params;
#uwsgi_pass 127.0.0.1:9990;
uwsgi_pass unix:/usr/local/share/hello.sock;
}
}
用任意用戶(hù)(最好不是root)在程序目錄下運(yùn)行uwsgi --ini hello.ini或者通過(guò)systemd運(yùn)行程序即可。