原來使用Apache2和mod_wsgi來部署flask程序,用起來挺好。后來程序更新后安裝mod_wsgi一直成問題,所以就放棄了,決定采用uWsgi和nginx組合。
uwsgi的配置
uwsgi的配置文件不算太復雜,按以下格式配置即可:
[uwsgi]
socket = 127.0.0.1:8000 #注: 指定某個固定端口
processes = 4 #注:跑幾個進程,這里用4個進程
threads = 2
master = true
module = worksite
callable = app
memory-report = true
touch-reload = /usr/local/etc/uwsgi.ini
logto = /usr/local/var/log/uwsgi.log
wsgi-disable-file-wrapper = true
其中最后一項是因為使用Flask下載文件時采用動態生成的方式,采用了BytesIO模塊,下載時直接報錯。Google了一些文章才知道要加上這么一句。
這個文件保存為uwsgi.ini,放在/usr/local/etc/目錄下即可。
nginx的配置
nginx的配置也不復雜,主要配置如下:
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8000;
# root html;
# index index.html index.htm;
}
location /static/ {
root /usr/local/var/worksite/;
}
location /upload/ {
root /usr/local/var/worksite/;
}
location /image/ {
alias /Users/huangtao/OneDrive/圖片/本機照片/;
autoindex on;
}
}
}
核心的一句在location / 通過“uwsgi_pass 127.0.0.1:8000;”將其轉發給uwsgi來處理。
其他的一些配置均為靜態文件的配置。
上述配置文件為/usr/local/etc/nginx/nginx.conf
自動啟動上述服務
要想讓上述服務自動啟動,需要配置相應的plist文件,主要有兩個。
- 一個是uwsgi.plist,文件內容為:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>uwsgi</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/uwsgi</string>
<string>/usr/local/etc/uwsgi.ini</string>
</array>
</dict>
</plist>
- 第二個是nginx.plist,其內容是:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/nginx</string>
<string>-c</string>
<string>/usr/local/etc/nginx/nginx.conf</string>
</array>
<key>Label</key>
<string>nginx</string>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
上述文件編輯完成后,將其放入/Library/LaunchDaemons/目錄下即可。重啟系統即可看到上述服務已經啟動。