采用Nginx + Gunicorn
1 项目环境准备
新建项目文件夹
$ sudo mkdir /var/www/rsda_server
安装virtualenv
$ sudo apt-get update
$ sudo pip3 install virtualenv
新建并激活虚拟环境
$ cd /var/www/rsda_server
$ sudo virtualenv venv
$ source ./venv/bin/activate
安装依赖包
(venv)$ pip3 install Flask
新建测试app
(venv)$ sudo vim hello.py
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix # 生产环境中加入
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello super man!"
app.wsgi_app = ProxyFix(app.wsgi_app) # 生产环境中加入
if __name__ == '__main__':
app.run()
新建logs文件夹
(venv)$ sudo mkdir logs
2安装配置Gunicorn
(venv)$ sudo pip3 install gunicorn
gunicorn相关命令:
gunicorn -h # 命令列表
gunicorn -b ip:port # 挂载服务, ip:port 默认为:127.0.0.1:8000
gunicorn -w n # 开启多个worker,n : worker,2~4之间
3安装配置Nginx
(venv)$ sudo apt-get install nginx
安装nginx时可能会报错,提示端口被占用,如下图:
删除默认配置文件,这里采用备份操作
(venv)$ cd /etc/nginx/sites-available
(venv)$ sudo mv default default.bak
>参考: https://stackoverflow.com/questions/14972792/nginx-nginx-emerg-bind-to-80-failed-98-address-already-in-use
新建配置文件
(venv)$ sudo vim /etc/nginx/sites-available/hello.conf
server {
listen 5050; # 设置访问端口
server_name hello.com;
root /var/www/rsda_server;
access_log /var/www/rsda_server/logs/access.log;
error_log /var/www/rsda_server/logs/error.log;
location / {
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:8000;
break;
}
}
}
设置链接使得配置生效
(venv)$ sudo ln -s /etc/nginx/sites-available/hello.conf /etc/nginx/sites-enabled/
检查配置文件是否合法,如下输出表示配置文件合法,否则输出错误信息。
(venv)$ sudo nginx -t
4 运行服务
4.1启动nginx
(venv)$ sudo nginx start #启动
(venv)$ sudo service nginx reload # 重启
如果启动失败,提示端口被占用,可能是测试时启动的nginx服务占用了端口,找到杀之,再启动。
4.2 启动gunicorn
(venv)$ cd /var/www/rsda_server
(venv)$ sudo gunicorn -w 4 -b 127.0.0.1:8000 hello:app
访问地址:ip:5050
5 参考资料
- How to Run Flask Applications with Nginx Using Gunicorn
http://www.onurguzel.com/how-to-run-flask-applications-with-nginx-using-gunicorn/
- 在 Ubuntu 上使用 Nginx 部署 Flask 应用
https://www.oschina.net/translate/serving-flask-with-nginx-on-ubuntu
- Gunicorn 主页
http://docs.gunicorn.org/en/stable/deploy.html