Flask污力_机器学习fastapi

gunicorn 详解

2018-08-26  本文已影响4137人  慢手暗夜

Gunicorn是一个unix上被广泛使用的高性能的Python WSGI UNIX HTTP Server。
和大多数的web框架兼容,并具有实现简单,轻量级,高性能等特点。

gunicorn 安装

pip install gunicorn

gunicorn + flask 简单示例

flask程序需要先安装flask module,pip install flask。

gunicorn_demo.py

from flask import Flask

app = Flask(__name__)


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

通过gunicorn运行flask app

# gunicorn gunicorn_demo:app
[2017-12-23 10:36:09 +0000] [24441] [INFO] Starting gunicorn 19.7.1
[2017-12-23 10:36:09 +0000] [24441] [INFO] Listening at: http://127.0.0.1:8000 (24441)
[2017-12-23 10:36:09 +0000] [24441] [INFO] Using worker: sync
[2017-12-23 10:36:09 +0000] [24446] [INFO] Booting worker with pid: 24446

测试结果

# curl http://127.0.0.1:8000/demo
gunicorn and flask demo.

gunicorn 部署

gunicorn是一个wsgi http server,可以如上一章节所示直接起停,提供http服务。

不过在production环境,起停和状态的监控最好用supervisior之类的监控工具,然后在gunicorn的前端放置一个http proxy server, 譬如nginx。

下面是supervisor和nginx的配置。

supervisor_gunicorn.conf

[program:gunicorn_demo]
process_name=%(program_name)s
numprocs=1
priority=901
directory = /opt/gunicorn_demo/
command = /opt/virtualenv/bin/python /opt/virtualenv/bin/gunicorn -c gunicorn_demo.py gunicorn_demo:app
autostart = true
startsecs = 20
autorestart = true
startretries = 3
user = root
redirect_stderr = true
stdout_logfile_maxbytes = 20MB
stdout_logfile_backups = 10
stdout_logfile = /dev/null

-c gunicorn_demo.py, 即是gunicorn本身的配置文件,下面是gunicorn的基本配置,下一章节会详细说明gunicorn的配置项。

import multiprocessing

bind = '127.0.0.1:8000'
workers = multiprocessing.cpu_count() * 2 + 1

backlog = 2048
worker_class = "gevent"
worker_connections = 1000
daemon = False
debug = True
proc_name = 'gunicorn_demo'
pidfile = './log/gunicorn.pid'
errorlog = './log/gunicorn.log'

nginx.conf part

server {
    listen 80;
    server_name sam_rui.com;
    access_log  /var/log/nginx/access.log;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

gunicorn 详细配置

gunicorn配置项可以通过gunicorn的启动命令行中设定,也可以通过配置文件指定。强烈建议使用一个配置文件。

配置项如下:

server socket

worker 进程

security

调试

server 机制

日志

进程名

server钩子

上一篇下一篇

猜你喜欢

热点阅读