最近自己在使用用python做web项目,整理了一下flask部署到服务器的知识点

gunicorn

简介

gunicorn是一个给UNIX用的WSGIHTTP务器,同类的还有uwsgiTornado,配置简单,易于上手

安装

centos

1
yum install python-gunicorn

或者可以使用pip命令安装

1
2
pip install gunicorn # python2.7.5
pip3 install gunicorn # python3.x

注意:使用pip安装时要安装python-devel,否者安装后不能使用,如下

1
2
yum install python-devel # python2.7.5
yum search python3 | grep devel # python3.x

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# gunicorn.conf

workers = 4
threads = 2
bind = '127.0.0.1:8000'
daemon = 'false'
worker_class = 'gevent'
worker_connections = 2000
# python路径
pythonpath= '/usr/bin/python3'
pidfile = '/var/run/gunicorn.pid'
accesslog = '/home/wwwlogs/gunicorn_acess.log'
errorlog = '/home/wwwlogs/gunicorn_error.log'
loglevel = 'warning'

启动

1
2
3
4
5
6
7
# 简单的启动
gunicorn app:app
# 带其他参数的启动
gunicorn -w 1 -b 127.0.0.1:8080 app:app --pythonpath='/usr/bin/python3'
# 不知道为什么,我用命令行启动带上pythonpath始终没效的
# w是指进程数
# b是指地址和端口

app指的是app.py这个文件,是你项目的启动文件,app是指定义falsk的那个app变量

supervisor

安装

注意,supervisor只支持python2.7版本

1
easy_install supervisor

生成默认的配置文件

1
echo_supervisord_config > supervisord.conf

配置

1
2
3
4
5
6
7
8
9
10
11
[program:minstorm_flask]
# 运行的命令
command=/usr/bin/gunicorn -c /home/wwwroot/gunicorn.conf manage:app
# 运行命令前进入的目录
directory=/home/wwwroot/flask_env/minstorm_flask
startsecs=0
stopwaitsecs=0
autostart=true
autorestart=true
stdout_logfile=/home/wwwlogs/supervisor_access.log
stderr_logfile=/home/wwwlogs/supervisor_error.log

首先运行这个命令

1
supervisord -c /etc/supervisord.conf

然后再运行这个命令

1
supervisorctl -c /etc/supervisord.conf

nginx配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server
{
listen 80;
server_name xxx.xxxx.com xxx.xxxx.com;
location /static/ {
alias /xxx/xxx/xxx/minstorm_flask/app/static/;
}

location / {
proxy_pass http://127.0.0.1:8000;
proxy_redirect off;
proxy_set_header Host $host:8000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

access_log /xxxx/logs/xxx.xxx.com.log;
}