环境:CentOS 7.6,Python 3.6.8

两种方法,一种 supervisor,一种 docker

gunicorn + supervisor

使用 ftp 将项目文件传到服务器中

安装配置虚拟环境

1
2
3
4
5
6
$ yum install python-virtualenv
$ virturalenv venv
$ source ./venv/bin/activate

$ pip install -r requirements.txt
$ pip install gunicorn

安装配置 supervisor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$ yum install supervisor
$ systemctl start supervisor
$ systemctl enable supervisor

$ vim /etc/supervisord.conf
# 最后一行将 .ini 改为 .conf
...
[include]
files = supervisord.d/*.conf

$ systemctl restart supervisor
$ vim /etc/supervisord.d/flask-blog.conf

[program:flask-blog]
command=/root/flask-blog/venv/bin/gunicorn -w 2 -b 0.0.0.0:5000 app:app
directory=/root/flask-blog
autostart=true
autorestart=true
user=root
redirect_stderr=true

$ supervisorctl status
flask-blog RUNNING pid 1921, uptime 1:07:41
$ netstat -tunlp | grep 5000
tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN 1921/python

notes:更改 conf 文件需要执行 supervisorctl update 加载新的配置,否则会报错无法重新 start

预览地址:http://81.68.234.158:5000

gunicorn + docker

使用 ftp 将项目文件传到服务器中

确保已安装 docker 环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ vim requirements.txt

flask
gunicorn
gevent

$ vim gunicorn.conf.py

workers = 5
worker_class = 'gevent'
bind = '0.0.0.0:8848'

$ vim Dockerfile

FROM python:3
WORKDIR /root/flask-demo
COPY . .
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
CMD ["gunicorn", "app:app", "-c", "./gunicorn.conf.py"]

$ docker build -t flask-demo .
$ docker run -d -p 8848:8848 --name flask-demo flask-demo

预览地址:http://81.68.234.158:8848

参考文章:https://zhuanlan.zhihu.com/p/78432719