Python:Flask部署Nginx、gunicorn、gevent、flask

安装

pip install gunicorn gevent flask

flask应用

# -*- coding: utf-8 -*-
# run.py

from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)

@app.route('/')
def hello_world():
    return 'Hello World!'


命令行启动

gunicorn -w 2 -b 127.0.0.1:8000 run:app

配置文件

# -*- coding: utf-8 -*-
# config.py

from __future__ import print_function, absolute_import, unicode_literals

import multiprocessing
import os

import gevent.monkey

gevent.monkey.patch_all()

if not os.path.exists('log'):
    os.mkdir('log')

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

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

指定配置文件启动

gunicorn -c config.py run:app

关闭

# 查看PID号
ps -ef | grep gunicorn

# 或者
cat log/gunicorn.pid


# 停止
kill -9 PID号
# 重启
kill -HUP PID号

整合成命令行

#!/bin/bash
# service.sh

# 添加启动命令
function start(){
    echo "start..."
    # 此处修改为项目路径

    gunicorn -c config.py app:app

    echo "start successful"
    return 0
}

# 添加停止命令
function stop(){
    echo "stop..."

    kill -9 `cat log/gunicorn.pid`

    echo "stop successful"
    return 0
}

# 重启
function restart(){
    echo "restart..."

    kill -HUP `cat log/gunicorn.pid`

    echo "restart successful"
    return 0
}

case $1 in
"start")
    start
    ;;
"stop")
    stop
    ;;
"restart")
    restart
    ;;
*)
    echo "请输入: start, stop, restart"
    ;;
esac

Nginx配置

server {
    listen 80;

    server_name _;

    access_log  /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    location / {
        proxy_pass         http://127.0.0.1:5000/;
        proxy_redirect     off;

        proxy_set_header   Host                 $host;
        proxy_set_header   X-Real-IP            $remote_addr;
        proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto    $scheme;
    }
}

Python Web 腾讯云部署:flask+fabric+gunicorn+nginx+supervisor
gunicorn 部署 flask

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页