安装flask
pip install flask
测试flask是否安装成功,使用flask写一个简单的web服务。路径为/usr/local/myproject文件夹
gedit test.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'hello world'
if __name__ == '__main__':
app.run()
运行
python test.py
此时,用浏览器访问 http://127.0.0.1:5000 就能看到网页显示 hello world。
安装gunicorn
pip install gunicorn
当我们安装好gunicorn之后,需要用gunicorn来启动 flask,注意 flask 里面的name里面的代码启动了 app.run(),这个含义是用 flask 自带的服务器启动 app;这里我们使用gunicorn,test.py 就等同于一个库文件,被gunicorn调用。
gunicorn -w4 -b0.0.0.0:8000 test:app
此时,我们需要用8000端口进行访问,原先的5000并没有启用。其中gunicorn的部署中:-w 表示开启多少个worker,-b表示gunicorn开发的访问地址。
想结束gunicorn只需执行pkill gunicorn,有时候还得ps找到pid进程号才能kill。可是这对于一个开发来说,太过于繁琐,因此出现了另外一个神器supervisor
,一个专门用来管理进程的工具,还可以管理系统的工具进程。
安装supervisor
pip install supervisor
echo_supervisord_conf > supervisor.conf # 生成 supervisor 默认配置文件
执行路径为/usr/local/myproject
gedit supervisor.conf # 修改 supervisor 配置文件,添加 gunicorn 进程管理
[program:test]
command=gunicorn -w4 -b0.0.0.0:2170 test:app ;supervisor启动命令
directory=/usr/local/myproject ; 项目的文件夹路径
startsecs=0 ; 启动时间
stopwaitsecs=0 ; 终止等待时间
autostart=false ; 是否自动启动
autorestart=false ; 是否自动重启
stdout_logfile=/usr/local/myproject/log/gunicorn.log ; log 日志
stderr_logfile=/usr/local/myproject/log/gunicorn.err ; 错误日志
现在可以使用 supervsior 启动 gunicorn啦。运行命令:
supervisord -c supervisor.conf
访问http://127.0.0.1:2170可以看见gunciron启动的返回的 hello world。
多次执行或更新supervisor.conf文件后,运行命令报错:
Error: Another program is already listening on a port that one of our HTTP servers is configured to use. Shut this program down first before starting supervisord.
解决办法:
1,首先进入supervisor控制台,运行命令:
supervisorctl
2,重新读取配置:
reread
3,更新配置:
update
4,开始所有配置:
start all
5,查看所有状态:
status
安装配置nginx
采用 apt-get方式安装最简单。运行 sudo apt-get install nginx
。安装好的nginx的二进制文件放在 /usr/sbin/
文件夹下面。而nginx的配置文件放在 /etc/nginx
下面。
使用 supervisor 来管理 nginx。这里需要注意一个问题,linux的权限问题。nginx是sudo的方式安装,启动的适合也是 root用户,那么我们现在也需要用 root用户启动supervisor。编辑supervisor.conf文件,添加如下内容:
(注意:nginx可能会不停重启,需要在command命令行加-g 'daemon off;'表示在前台运行)
[program:nginx]
command=/usr/sbin/nginx -g 'daemon off;'
startsecs=0
stopwaitsecs=0
autostart=true
autorestart=true
stdout_logfile=/usr/local/myproject/log/nginx.log
stderr_logfile=/usr/local/myproject/log/nginx.err
Nginx相关命令:
#配置重加载
nginx -s reload
#nginx停止与关闭
#切换到/usr/sbin目录
----停止
sudo ./nginx -s stop
----启动
./nginx