原来使用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/目录下即可。重启系统即可看到上述服务已经启动。