Gunicorn--pythonweb容器

Gunicorn 绿色独角兽'是一个Python WSGI UNIX的HTTP服务器。

是一个pre-fork worker的模型,从Ruby的独角兽(Unicorn )项目移植。

该Gunicorn服务器大致与各种Web框架兼容,只需非常简单的执行,轻量级的资源消耗,以及相当迅速,具有实现简单,轻量级,高性能等特点。

gunicorn是一个wsgi http server,可以直接起停,提供http服务。

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

特点:

  • 本身支持WSGI、Django、Paster

  • 自动辅助进程管理

  • 简单的 Python配置

  • 允许配置多个工作环境

  • 各种服务器的可扩展钩子

  • 与 Python 2.x > = 2.5,3.x >= 3.2 兼容

 

与 uWSGI 的性能比较:

gunicorn命令

  Gunicorn server的最基本的命令,直接用来运行最基本的 wsgi application 。

  用法:

gunicorn [OPTIONS] APP_MODULE
ie: gunicorn [OPTIONS] 模块名:变量名
  • OPTIONS 可选参数 运行gunicorn的配置选项,后面会讲到。
  • APP_MODULE 指定 wsgi application文件,书写格式 $(MODULE_NAME):$(VARIABLE_NAME)。

     其中 module_name用来制定将要运行的 wsgi application文件,可是一个完整的点缀名。

     比如当前目录 myapp 目录下有个 Python 包  gunicorn_app, gunicorn_app包下有一个wsgi application文件 test.py 则 module_name可以直接写成  gunicorn_app.test。

     variable_name表示在 module_name 文件中要调用的对象(是一个WSGI callable, 可以是一个函数,类详情参看WSGI规格说明书)名。

详细案例

gunicorn_demo.py

from flask import Flask

app = Flask(__name__)


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

启动:

gunicorn --workers 1 -k gevent --timeout 120 --bind 0.0.0.0:8182  "gunicorn_demo:app" --daemon --error-logfile error.log

 

 测试结果:

 

gunicorn 详细配置

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

配置项如下:

server socket

  • bind
    监听地址和端口。

  • backlog
    服务器中在pending状态的最大连接数,即client处于waiting的数目。超过这个数目, client连接会得到一个error。
    建议值64-2048。

worker 进程

  • workers
    worker进程的数量。建议值2-4 x $(NUM_CORES), 缺省为1。

  • worker_class
    worker进程的工作方式。 有 sync, eventlet, gevent, tornado, gthread, 缺省值sync。

  • threads
    工作进程中线程的数量。建议值2-4 x $(NUM_CORES), 缺省值1。
    此配置只适用于gthread 进程工作方式, 因为gevent这种使用的是协程工作方式。

  • worker_connections
    客户端最大同时连接数。只适用于eventlet, gevent工作方式。

  • max_requests
    worker重启之前处理的最大requests数, 缺省值为0表示自动重启disabled。主要是防止内存泄露。

  • max_requests_jitter
    抖动参数,防止worker全部同时重启。

  • timeout
    通常设为30。

  • graceful_timeout
    接收到restart信号后,worker可以在graceful_timeout时间内,继续处理完当前requests。

  • keepalive
    server端保持连接时间。

security

  • limit_request_line
    http request line最大字节数。值范围0-8190, 0表示无限制。

  • limit_request_field
    http request中 header字段数的最大值。缺省为100,最大32768。

  • limit_request_field_size
    http request header字段最大字节数。0表示无限制。

调试

  • reload
    当代码有修改时,自动重启workers。适用于开发环境。

  • reload_extra_files
    扩展reload配置,增加templates,configurations等文件修改监控。

  • spew
    跟踪程序执行的每一行。

  • check_config
    检查配置。

server 机制

  • sendfile
    系统底层拷贝数据方式,提供performance。

  • chdir
    在app加载之前,进入到此目录。

  • daemon
    应用是否以daemon方式运行。

  • raw_env
    key=value, 传递环境参数。

  • pidfile
    pid存储文件路径。

  • worker_tmp_dir
    临时工作目录。

  • user
    指定worker进程的运行用户名。

  • group
    指定worker进程运行用户所在组。

  • umask
    gunicorn创建文件的缺省权限。

  • pythonpath
    附加到python path的目录列表。

日志

  • accesslog
    访问日志文件路径。

  • access_log_format
    日志格式。 例如 %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" 。

  • errorlog
    错误日志路径。

  • loglever
    日志级别。debug, info, warning, error, critical.

  • capture_output
    重定向stdout/stderr到error log file。

  • logger_class
    日志实现类。缺省gunicorn.glogging.Logger 。

  • logconfig
    日志配置文件。同python标准日志模块logging的配置。

进程名

  • proc_name
    设置进程名(setproctitle),在ps,top等命令中会看到. 缺省值为default_proc_name配置。

server钩子

  • on_starting
  • on_reload
  • when_ready
  • pre_fork
  • post_fork
  • post_worker_init
  • worker_init
  • worker_abort
  • pre_exec
  • pre_request
  • post_request
  • child_exit
  • worker-exit
  • nworkers_changed
  • on_exit

命令行参数设置

(superset) [root@wqbin app]# gunicorn -h
usage: gunicorn [OPTIONS] [APP_MODULE]

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  -c CONFIG, --config CONFIG
                        The Gunicorn config file. [None]
  -b ADDRESS, --bind ADDRESS
                        The socket to bind. [['127.0.0.1:8000']]
  --backlog INT         The maximum number of pending connections. [2048]
  -w INT, --workers INT
                        The number of worker processes for handling requests.
                        [1]
  -k STRING, --worker-class STRING
                        The type of workers to use. [sync]
  --threads INT         The number of worker threads for handling requests.
                        [1]
  --worker-connections INT
                        The maximum number of simultaneous clients. [1000]
  --max-requests INT    The maximum number of requests a worker will process
                        before restarting. [0]
  --max-requests-jitter INT
                        The maximum jitter to add to the *max_requests*
                        setting. [0]
  -t INT, --timeout INT
                        Workers silent for more than this many seconds are
                        killed and restarted. [30]
  --graceful-timeout INT
                        Timeout for graceful workers restart. [30]
  --keep-alive INT      The number of seconds to wait for requests on a Keep-
                        Alive connection. [2]
  --limit-request-line INT
                        The maximum size of HTTP request line in bytes. [4094]
  --limit-request-fields INT
                        Limit the number of HTTP headers fields in a request.
                        [100]
  --limit-request-field_size INT
                        Limit the allowed size of an HTTP request header
                        field. [8190]
  --reload              Restart workers when code changes. [False]
  --reload-engine STRING
                        The implementation that should be used to power
                        :ref:`reload`. [auto]
  --reload-extra-file FILES
                        Extends :ref:`reload` option to also watch and reload
                        on additional files [[]]
  --spew                Install a trace function that spews every line
                        executed by the server. [False]
  --check-config        Check the configuration. [False]
  --preload             Load application code before the worker processes are
                        forked. [False]
  --no-sendfile         Disables the use of ``sendfile()``. [None]
  --reuse-port          Set the ``SO_REUSEPORT`` flag on the listening socket.
                        [False]
  --chdir CHDIR         Chdir to specified directory before apps loading.
                        [/root/miniconda3/envs/superset/lib/python3.6/site-
                        packages/gunicorn/app]
  -D, --daemon          Daemonize the Gunicorn process. [False]
  -e ENV, --env ENV     Set environment variable (key=value). [[]]
  -p FILE, --pid FILE   A filename to use for the PID file. [None]
  --worker-tmp-dir DIR  A directory to use for the worker heartbeat temporary
                        file. [None]
  -u USER, --user USER  Switch worker processes to run as this user. [0]
  -g GROUP, --group GROUP
                        Switch worker process to run as this group. [0]
  -m INT, --umask INT   A bit mask for the file mode on files written by
                        Gunicorn. [0]
  --initgroups          If true, set the worker process's group access list
                        with all of the [False]
  --forwarded-allow-ips STRING
                        Front-end's IPs from which allowed to handle set
                        secure headers. [127.0.0.1]
  --access-logfile FILE
                        The Access log file to write to. [None]
  --disable-redirect-access-to-syslog
                        Disable redirect access logs to syslog. [False]
  --access-logformat STRING
                        The access log format. [%(h)s %(l)s %(u)s %(t)s
                        "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"]
  --error-logfile FILE, --log-file FILE
                        The Error log file to write to. [-]
  --log-level LEVEL     The granularity of Error log outputs. [info]
  --capture-output      Redirect stdout/stderr to specified file in
                        :ref:`errorlog`. [False]
  --logger-class STRING
                        The logger you want to use to log events in Gunicorn.
                        [gunicorn.glogging.Logger]
  --log-config FILE     The log config file to use. [None]
  --log-config-dict LOGCONFIG_DICT
                        The log config dictionary to use, using the standard
                        Python [{}]
  --log-syslog-to SYSLOG_ADDR
                        Address to send syslog messages. [udp://localhost:514]
  --log-syslog          Send *Gunicorn* logs to syslog. [False]
  --log-syslog-prefix SYSLOG_PREFIX
                        Makes Gunicorn use the parameter as program-name in
                        the syslog entries. [None]
  --log-syslog-facility SYSLOG_FACILITY
                        Syslog facility name [user]
  -R, --enable-stdio-inheritance
                        Enable stdio inheritance. [False]
  --statsd-host STATSD_ADDR
                        ``host:port`` of the statsd server to log to. [None]
  --dogstatsd-tags DOGSTATSD_TAGS
                        A comma-delimited list of datadog statsd (dogstatsd)
                        tags to append to statsd metrics. []
  --statsd-prefix STATSD_PREFIX
                        Prefix to use when emitting statsd metrics (a trailing
                        ``.`` is added, []
  -n STRING, --name STRING
                        A base to use with setproctitle for process naming.
                        [None]
  --pythonpath STRING   A comma-separated list of directories to add to the
                        Python path. [None]
  --paste STRING, --paster STRING
                        Load a PasteDeploy config file. The argument may
                        contain a ``#`` [None]
  --proxy-protocol      Enable detect PROXY protocol (PROXY mode). [False]
  --proxy-allow-from PROXY_ALLOW_IPS
                        Front-end's IPs from which allowed accept proxy
                        requests (comma separate). [127.0.0.1]
  --keyfile FILE        SSL key file [None]
  --certfile FILE       SSL certificate file [None]
  --ssl-version SSL_VERSION
                        SSL version to use. [_SSLMethod.PROTOCOL_TLS]
  --cert-reqs CERT_REQS
                        Whether client certificate is required (see stdlib ssl
                        module's) [VerifyMode.CERT_NONE]
  --ca-certs FILE       CA certificates file [None]
  --suppress-ragged-eofs
                        Suppress ragged EOFs (see stdlib ssl module's) [True]
  --do-handshake-on-connect
                        Whether to perform SSL handshake on socket connect
                        (see stdlib ssl module's) [False]
  --ciphers CIPHERS     SSL Cipher suite to use, in the format of an OpenSSL
                        cipher list. [None]
  --paste-global CONF   Set a PasteDeploy global config variable in
                        ``key=value`` form. [[]]
  --strip-header-spaces
                        Strip spaces present between the header name and the
                        the ``:``. [False]

完结!~!

 

 

 

 

 

posted @ 2020-07-29 09:22  wqbin  阅读(821)  评论(0编辑  收藏  举报