参考:
https://www.cnblogs.com/Pushy/p/8453218.html
https://www.jianshu.com/p/837164e9f724
准备工作:
1、安装python环境:apt-get install python-dev
2、安装flask:pip install flask
3、安装Gunicorn:pip install gunicorn
4、安装Nginx:apt-get install nginx
5、安装supervisor:apt-get install supervisor
6、安装gevent:pip install gevent
环境部署:
这里以一个比较简单的项目为例,项目绝对路径为/home/test,项目名称为test,flask文件为webtest.py,其中webtest.py文件如下:
#webtest.py
from flask import Flask,request
app = Flask(__name__)
@app.route('/')
def home():
return "home"
if __name__ == '__main__':
app.run(debug=False)
1、部署Gunicorn
这里有两种方法:
一是直接部署:项目文件下执行,gunicorn -w 4 -b 172.xx.x.xx:8000 webtest:app,其中172.21.0.xx:8000为内网ip和端口号,webtest为py文件。
二是配置文件部署:在项目文件夹下创建两个文件,conf、log。conf文件下新建guni.py用来配置Gunicorn。
from gevent import monkey
monkey.patch_all()
import multiprocessing
debug = True
loglevel = 'debug'
bind = '172.xx.x.xx:8000'
pidfile = 'log/gunicorn.pid'
logfile = 'log/debug.log'
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = 'gevent'
在项目文件夹下,使用命令gunicorn -c conf/guni.py webtest:app。
以上gunicorn就部署完了。
2、部署Nginx
使用命令:sudo vim /etc/nginx/sites-enabled/default
将配置文件修改为:
server {
listen 80;
server_name xx.xxx.xxx.xx; //公网ip
location / {
proxy_pass http://xxx.xx.xx.xx:8000; //内网ip
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
重启Nginx:service nginx restart
3、部署supervisor
通过以上方式不能在后台运行,通过部署supervisor可以在后台运行并且能够监控进程状态。
第一步:在/etc/supervisor/conf.d/
目录下创建我们控制进程的配置文件,并以.conf结尾,文件名可以随意取,我这里与py文件相同。sudo vim /etc/supervisor/conf.d/webtest.conf。
更改配置文件为:
[program:webtest] //(这里program:后是进程名,自己起)
command=gunicorn -c /home/test/conf/guni.py webtest:app
directory=/home/test //项目绝对地址
user=root
autorestart=true
startretires=3
这里command命令与之前的gunicorn一致,只不过需要使用绝对路径,也可以换成gunicorn -w 4 -b 172.xx.x.xx:8000 webtest:app,但是如果gunicorn安装在虚拟环境下,需要使用绝对路径,例如 /www/demo/venv/bin/gunicorn -w 4 -b 172.xx.x.xx:8000 webtest:app。
第二步:更新配置文件supervisorctl update
启动进程:supervisorctl start webtest
第三步:自此就配置完了,可以通过supervisorctl命令查看当前进程状态。
stop webtest 停止该进程
start webtest 启动该进程