【Gunicorn】Gunicorn安装&相关配置&脚本

1. Gunicorn介绍

官网
官方文档

Gunicorn(绿色独角兽)是一个Python WSGI的HTTP服务器。
从Ruby的独角兽(Unicorn )项目移植
该Gunicorn服务器与各种Web框架兼容,实现非常简单,轻量级的资源消耗
Gunicorn直接用命令启动,不需要编写配置文件

2. Gunicorn安装

pip install gunicorn

查看选项

gunicorn -h

3. 配置参数

常用配置参数说明如下。更多点击链接官网查看

3.1 命令行参数

不建议在命令行中配置很多的参数

-c  # 配置文件
-w  # 表示进程(worker)
-b  # 表示绑定ip地址和端口号(bind) 
-D  # 守护进程
--reload  # 自动刷新 (更新代码,自动刷新 debug时可用) **不建议

gunicorn -w 2 -b 127.0.0.1:7000 运行文件名称:Flask程序实例名

命令行示例

gunicorn -w 2 -b 0.0.0.0:7000 app:app -D --reload

3.2 配置文件参数

【强烈建议】在配置文件中进行相关配置
官网配置参数
使用说明参照下图
在这里插入图片描述

配置文件示例

import multiprocessing

from pathlib import Path

bind = "127.0.0.1:8000"
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = 'gevent'
threads = workers * 2
keepalive = 5
accesslog = str(Path.joinpath(Path.cwd(), 'static', 'log', 'gunicorn_access.log'))
errorlog = str(Path.joinpath(Path.cwd(), 'static', 'log', 'gunicorn_err.log'))
access_log_format = '%({X-Real-IP}i)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

用户访问日志相关的配置

# 指定用户访问的日志文件
accesslog = str(Path.joinpath(Path.cwd(), 'static', 'log', 'gunicorn_access.log'))
# 存储的日志格式
access_log_format = '%({X-Real-IP}i)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

从配置文件中读取的命令行示例

gunicorn -c gunicorn.py app:APP -D

4. Gunicorn日志中获取用户真实IP

Nginx中配置proxy_set_header X-Real-IP $remote_addr;
Nginx示例:

location / {
                # 请求转发到gunicorn服务器
                proxy_pass http://127.0.0.1:5000;
                
                # 请求转发到多个gunicorn服务器
                # proxy_pass http://flask;
                
                # 设置请求头,并将头信息传递给服务器端 
                proxy_set_header Host $host;
                
                # 设置请求头,传递原始请求ip给 gunicorn 服务器
                proxy_set_header X-Real-IP $remote_addr;
                
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

Gunicorn日志配置示例

# i表示 request header
access_log_format = '%({X-Real-IP}i)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

5. Shell脚本示例

因运行在Docker容器中服务需要经常性重启,且容器中只运行了一种类型Gunicorn服务,且为防止误杀进程,简单写了如下的重启脚本

#!/bin/bash

containerName="test"
currTime="date +'%Y-%m-%d %H:%M:%S'"
exist="docker inspect --format '{{.State.Running}}' ${containerName}"
if [ $? -ne 0 ] || [ "${exist}" != "true" ]; then
  # 判断说明: 上行命令执行失败 或者 不存在指定的容器时
  # 查找指定名称的所有进程ID,并彻底杀死进程。 这里的指定名称是 gunicorn
  kill -9 "ps -ef | grep gunicorn | head -1 | awk '{print $2}'"
  gunicorn -c gunicorn.py app:APP -D
  echo "${currTime} Gunicorn服务重启"
else
  echo "${currTime} 请在对应容器内执行此脚本"
fi
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值