Linux + Nginx 下通过FastCGI 部属 Flask 应用
FastCGI是一种最常见的在如Nginx,Lighttpd和Cherokee等服务器上部属Flask应用的方法,当然,首先得先有一个FastCGI服务器,使用最多的就是Flup。
创建一个 .fcgi 文件
最开始需要创建一个FastCGI服务器文件,比如我的一个应用为costony,那么我可以把这个文件叫作: costony.fcgi :
#!/usr/bin/python
from flup.server.fcgi import WSGIServer
from costony import app
if __name__ == '__main__':
WSGIServer(app).run()
如果使用的Apache服务器的话,那么上面这些就已经足够了,但是Nginx或者老一些的Lighttpd服务器的话,还需要明显地把 socket 传送给 WSGIServer。
WSGIServer(app, bindAddress='/tmp/costony-fcgi.sock').run()
上一行的Socket路径应该与服务器配置文件里面的一样,保存 costony.fcgi 文件到任何一个你还可以找得到的地方,比如 : /home/wwwroot/costony.com/ 或者其它的类似的目录,然后需要让这个文件可执行:
#chmod +x /home/wwwroot/costony.com/costony.fcgi
配置 Lighttpd
基本的Lighttpd FastCGI配置如下:
fastcgi.server = ("/costony.fcgi" =>
((
"socket" => "/tmp/costony-fcgi.sock",
"bin-path" => "/home/wwwroot/costony.com/costony.fcgi",
"check-local" => "disable",
"max-procs" => 1
))
)
alias.url = (
"/static/" => "/home/wwwroot/costony.com/static"
)
url.rewrite-once = (
"^(/static.*)$" => "$1",
"^(/.*)$" => "/costony.fcgi$1"
)
别忘记必须开启FastCGI,Alias以及Rewrite模块。
配置 Nginx
Nginx有一些不同,它默认情况是没有FastCGI参数被发送的,所以一个基本的Nginx FastCGI配置如下:
location = /costony { rewrite ^ /costony/ last; }
location /costony { try_files $uri @costony; }
location @costony {
include fastcgi_params;
fastcgi_split_path_info ^(/costony)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_pass unix:/tmp/costony-fcgi.sock;
}
上面这个配置是让应用在 /costony 这一级目录被访问,如果像我一样,把应用直接放在根目录被访问的话,我们可以像下面这样:
location / { try_files $uri @costony; }
location @costony {
include fastcgi_params;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param SCRIPT_NAME "";
fastcgi_pass unix:/tmp/costony-fcgi.sock;
}
运行 FastCGI 进程
如果上面这样还不行的话,我们还需要主动运行FastCGI,运行下面这个命令:
$screen
$python /home/wwwroot/costony.com/costony.fcgi
之后我们还需要对这个Socket相应的权限:
$chmod 0777 /tmp/costony-fcgi.sock
评论已关闭