Flask+Gunicorn在乌班图上部署

Flask+Gunicorn在乌班图上部署

最近因为工作需要,学习了flask由于gunicorn在linux上的部署,这里对自己进行的尝试进行一个总结

1.Gunicorn介绍

Gunicorn是一个WSGI HTTP服务器,python自带的有个web服务器,叫做wsgiref,
Gunicorn的优势在于,它使用了pre-fork worker模式,gunicorn在启动时,会在主进程中预先fork出指定数量的worker进程来处理请求。

运用Gunicorn运行Flask

首先要确保安装gunicorn,本机系统为乌班图18.04

pip install gunicorn

安装成功后,在flask项目目录中可用gunicorn运行flask程序,其中flask文件如下:

myapp.py

import logging

from flask import Flask


app = Flask(__name__)

@app.route('/')
def index():
    data = b"Hello, World!\n"
    return data

@app.route('/demo', methods=['GET'])
def demo():
    return "gunicorn and flask demo."

运行命令为:gunicorn -w 4 myapp:app
输出结果如下
在这里插入图片描述
访问127.0.0.1:8000返回成功
在这里插入图片描述

2. 用Gunicorn配置文件运行Flask

配置文件命名为config.py,具体代码如下:

import os
#import gevent.monkey
#gevent.monkey.patch_all()

#import multiprocessing

# debug = True
loglevel = 'warning'
bind = "0.0.0.0:8000"
#pidfile = "log/gunicorn.pid"
#accesslog = "log/access.log"
#errorlog = "log/debug.log"
daemon = True

# 启动的进程数
#workers = multiprocessing.cpu_count()
workers = os.cpu_count()*2-1
#worker_class = 'gevent'
#x_forwarded_for_header = 'X-FORWARDED-FOR'

其中,注释的部分取消注释也可以正常运行。
以配置文件的方式运行flask,命令为:gunicorn -c config.py myapp:app
运行后控制台没输出,访问127.0.0.1:8000可正常返回字符串,运用ps -U命令查看gunicorn的相关进程
在这里插入图片描述
可看到,运行了4个相关进程,停止线程:pkill gunicorn
清除后再次用’ps -U neil-wang | grep gunicorn’命令查看,相关进程消失,访问127.0.0.1:8000没有返回。

3.用Systemd部署Flask+Gunicorn

首先,查看gunicorn的命令位置:
在这里插入图片描述
然后新建文件flask-demo.service文件,其具体内容如下:

[Unit]
Description = Flask Demo
After=network.target

[Service]
WorkingDirectory=/home/neil-wang/myproject
ExecStart=/home/neil-wang/anaconda3/bin/gunicorn -w 4 config.py myapp:app
Restart=on-failure

[Install]
WantedBy=multi-user.target

其中WorkingDirectory为flask项目工作目录,ExecStart为启动命令位置,这里用gunicorn -c config.py 未运行成功,具体原因未知,暂时未解决。
运行并查看:
在这里插入图片描述
访问127.0.0.1:8000可正常返回,停止与重新加载:
在这里插入图片描述
需要注意的是,每次关闭控制台并不会停止服务,若要停止服务需调用 systemctl stop 命令

4.总结

这是我的第一天进行的gunicorn+flask运行的尝试,进行的还比较有限并且没有测试过并发访问及结合nginx运行等相关情况,往后会继续补充和优化。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值