參考:https://www.jianshu.com/p/fecf15ad0c9a
https://www.cnblogs.com/nanrou/p/7026789.html 參數配置介紹
https://gunicorn.readthedocs.io/en/latest/ 中文文檔
https://www.cnblogs.com/xybaby/tag/gunicorn/ 源碼走讀
https://www.cnblogs.com/Ray-liang/p/4837850.html Flask + Gunicorn + Nginx 部署
Tips. pip --user用法
由於是部署在公司雲主機上,通常不會給root權限。之前都是提工單給SA sudo裝的,后來發現更安全也更方便的方法是pip install xxx --user,美中不足是安裝完以后需要手動添加PATHexport PATH=/home/username/.local/bin:$PATH
方便起見可以加到~/.bash_profile中
=============
主進程(master):主進程是一個簡單的循環,監聽各種進程的信號並做出相應的反應.它通過監聽信號(比如TTIN/TTOU/CHLD)來管理正在運行的工作進程.TTIN和TTOU告訴主進程增加或減少工作的進程數量.CHLD表明一個子進程被終止了,這時主進程就重啟這個失敗的進程
在應用啟動之后,然后再通過TTIN和TTOU這兩個信號來調整worker數量。
==============
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 --proxy-protocol Enable detect PROXY protocol (PROXY mode). [False] --worker-connections INT The maximum number of simultaneous clients. [1000] --statsd-host STATSD_ADDR ``host:port`` of the statsd server to log to. [None] --max-requests-jitter INT The maximum jitter to add to the *max_requests* setting. [0] --pythonpath STRING A comma-separated list of directories to add to the Python path. [None] -R, --enable-stdio-inheritance Enable stdio inheritance. [False] -k STRING, --worker-class STRING The type of workers to use. [sync] --ssl-version SSL_VERSION SSL version to use (see stdlib ssl module's) [3] --suppress-ragged-eofs Suppress ragged EOFs (see stdlib ssl module's) [True] --log-syslog Send *Gunicorn* logs to syslog. [False] --log-syslog-facility SYSLOG_FACILITY Syslog facility name [user] --cert-reqs CERT_REQS Whether client certificate is required (see stdlib ssl module's) [0] --preload Load application code before the worker processes are forked. [False] --keep-alive INT The number of seconds to wait for requests on a Keep- Alive connection. [2] --access-logfile FILE The Access log file to write to. [None] -g GROUP, --group GROUP Switch worker process to run as this group. [0] --graceful-timeout INT Timeout for graceful workers restart. [30] --do-handshake-on-connect Whether to perform SSL handshake on socket connect (see stdlib ssl module's) [False] --spew Install a trace function that spews every line executed by the server. [False] -w INT, --workers INT The number of worker processes for handling requests. [1] -n STRING, --name STRING A base to use with setproctitle for process naming. [None] --no-sendfile Disables the use of ``sendfile()``. [None] -p FILE, --pid FILE A filename to use for the PID file. [None] -m INT, --umask INT A bit mask for the file mode on files written by Gunicorn. [0] --worker-tmp-dir DIR A directory to use for the worker heartbeat temporary file. [None] --limit-request-fields INT Limit the number of HTTP headers fields in a request. [100] -c CONFIG, --config CONFIG The Gunicorn config file. [None] --log-config FILE The log config file to use. [None] --check-config Check the configuration. [False] --statsd-prefix STATSD_PREFIX Prefix to use when emitting statsd metrics (a trailing ``.`` is added, [] --proxy-allow-from PROXY_ALLOW_IPS Front-end's IPs from which allowed accept proxy requests (comma separate). [127.0.0.1] -u USER, --user USER Switch worker processes to run as this user. [0] --forwarded-allow-ips STRING Front-end's IPs from which allowed to handle set secure headers. [127.0.0.1] --threads INT The number of worker threads for handling requests. [1] --max-requests INT The maximum number of requests a worker will process before restarting. [0] --limit-request-line INT The maximum size of HTTP request line in bytes. [4094] --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"] --certfile FILE SSL certificate file [None] --chdir CHDIR Chdir to specified directory before apps loading. [/poc/poc] --paste STRING, --paster STRING Load a PasteDeploy config file. The argument may contain a ``#`` [None] --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 Error log. [False] --log-syslog-to SYSLOG_ADDR Address to send syslog messages. [udp://localhost:514] --log-syslog-prefix SYSLOG_PREFIX Makes Gunicorn use the parameter as program-name in the syslog entries. [None] -D, --daemon Daemonize the Gunicorn process. [False] --ciphers CIPHERS Ciphers to use (see stdlib ssl module's) [TLSv1] -b ADDRESS, --bind ADDRESS The socket to bind. [['127.0.0.1:8000']] -e ENV, --env ENV Set environment variable (key=value). [[]] --reload Restart workers when code changes. [False] --limit-request-field_size INT Limit the allowed size of an HTTP request header field. [8190] -t INT, --timeout INT Workers silent for more than this many seconds are killed and restarted. [30] --ca-certs FILE CA certificates file [None] --settings STRING The Python path to a Django settings module. (deprecated) [None] --keyfile FILE SSL key file [None] --backlog INT The maximum number of pending connections. [2048] --logger-class STRING The logger you want to use to log events in Gunicorn. [gunicorn.glogging.Logger]
示例:gunicorn -b 0.0.0.0:8080 -w 5 --log-file /var/log/poc/app.log --access-logfile /var/log/poc/app.acc --pid /var/log/poc/app.pid gf:app
gunicorn -b 0.0.0.0:8080 -w 5 --threads=3 --worker-class=gthread --log-file /var/log/poc/app.log --access-logfile /var/log/poc/app.acc --pid /var/log/poc/app.pid gf:app

/var/log/poc 這個目錄要事先存在,否則報錯
=============
# config.py import os import gevent.monkey gevent.monkey.patch_all() import multiprocessing # debug = True loglevel = 'debug' bind = "0.0.0.0:7001" pidfile = "log/gunicorn.pid" accesslog = "log/access.log" errorlog = "log/debug.log" daemon = True # 啟動的進程數 workers = multiprocessing.cpu_count() worker_class = 'gevent' x_forwarded_for_header = 'X-FORWARDED-FOR'
===========關於如何配置 Gunicorn 的實用建議=======
轉載:http://www.cocoachina.com/articles/27824

Gunicorn 是一個 Python 的 WSGI HTTP 服務器。它所在的位置通常是在反向代理(如 Nginx)或者 負載均衡(如 AWS ELB)和一個 web 應用(比如 Django 或者 Flask)之間
- 主進程的作用是確保 worker 數量與設置中定義的數量相同。因此如果任何一個 worker 掛掉,主線程都可以通過分發它自身而另行啟動。
- worker 的角色是處理 HTTP 請求。
第一種並發方式(workers 模式,又名 UNIX 進程模式)
每個 worker 都是一個加載 Python 應用程序的 UNIX 進程。worker 之間沒有共享內存。
建議的 workers 數量是 (2*CPU)+1。
對於一個雙核(兩個CPU)機器,5 就是建議的 worker 數量。
gunicorn --workers=5 main:app
第二種並發方式(多線程)
Gunicorn 還允許每個 worker 擁有多個線程。在這種場景下,Python 應用程序每個 worker 都會加載一次,同一個 worker 生成的每個線程共享相同的內存空間。
為了在 Gunicorn 中使用多線程。我們使用了 threads 模式。每一次我們使用 threads 模式,worker 的類就會是 gthread:
gunicorn --workers=5 --threads=2 --worker-class=gthread main:app
在使用 worker 和多線程模式時建議的最大並發數量仍然是(2*CPU)+1。
因此如果我們使用四核(4 個 CPU)機器並且我們想使用 workers 和多線程模式,我們可以使用 3 個 worker 和 3 個線程來得到最大為 9 的並發請求數量。
gunicorn --workers=3 --threads=3 --worker-class=gthread main:app
第三種並發方式(“偽線程”)
有一些 Python 庫比如(gevent 和 Asyncio)可以在 Python 中啟用多並發。那是基於協程實現的“偽線程”。
Gunicrn 允許通過設置對應的 worker 類來使用這些異步 Python 庫。這里的設置適用於我們想要在單核機器上運行的gevent:
gunicorn --worker-class=gevent --worker-connections=1000 --workers=3 main:app
worker-connections 是對於 gevent worker 類的特殊設置。
2*CPU)+1 仍然是建議的workers 數量。因為我們僅有一核,我們將會使用 3 個worker。
在這種情況下,最大的並發請求數量是 3000。(3 個 worker * 1000 個連接/worker)
通過調整Gunicorn設置,我們希望優化應用程序性能。
- 如果這個應用是 I/O 受限,通常可以通過使用“偽線程”(gevent 或 asyncio)來得到最佳性能。正如我們了解到的,Gunicorn 通過設置合適的 worker 類 並將
workers數量調整到(2*CPU)+1來支持這種編程范式。 -
mport multiprocessing workers = multiprocessing.cpu_count() * 2 + 1
- 如果這個應用是 CPU 受限,那么應用程序處理多少並發請求就並不重要。唯一重要的是並行請求的數量。因為 Python’s GIL,線程和“偽線程”並不能以並行模式執行。實現並行性的唯一方法是增加**
workers** 的數量到建議的(2*CPU)+1,理解到最大的並行請求數量其實就是核心數。 - 如果不確定應用程序的內存占用,使用
多線程以及相應的 gthread worker 類 會產生更好的性能,因為應用程序會在每個 worker 上都加載一次,並且在同一個 worker 上運行的每個線程都會共享一些內存,但這需要一些額外的 CPU 消耗。 - 如果你不知道你自己應該選擇什么就從最簡單的配置開始,就只是
workers數量設置為(2*CPU)+1並且不用考慮多線程。從這個點開始,就是所有測試和錯誤的基准環境。如果瓶頸在內存上,就開始引入多線程。如果瓶頸在 I/O 上,就考慮使用不同的 Python 編程范式。如果瓶頸在 CPU 上,就考慮添加更多內核並且調整workers數量
