Python Gunicorn服务器使用方法详解

林见深
林见深
发布时间:2026-10-14 | 1人浏览过
原创

本文详细介绍Gunicorn作为Unix环境下WSGI HTTP服务器的使用方法。涵盖基础启动命令、-w和-b参数的具体配置、Flask应用集成示例,以及解决端口占用和进程挂起等常见启动异常的技巧,帮助开发者快速部署高性能Web服务。

简介

Gunicorn(Green Unicorn)是一款专为Unix系统设计的高性能WSGI HTTP服务器。它具有与多种Web框架高度兼容、安装简便、轻量级以及运行速度快等特点。

示例代码1


def app(environ, start_response):
  data = b"Hello World\n"
  start_response("200 OK", [
    ("Content-Type", "test/plain"),
    ("Content-Length", str(len(data)))
  ])
  return iter([data])

启动


gunicorn -w 4 myapp:app

启动后终端显示如下信息:


[2016-12-12 00:20:12 +0000] [11755] [INFO] Starting gunicorn 19.6.0
[2016-12-12 00:20:12 +0000] [11755] [INFO] Listening at: http://127.0.0.1:8000 (11755)
[2016-12-12 00:20:12 +0000] [11755] [INFO] Using worker: sync
[2016-12-12 00:20:12 +0000] [11760] [INFO] Booting worker with pid: 11760
[2016-12-12 00:20:12 +0000] [11761] [INFO] Booting worker with pid: 11761
[2016-12-12 00:20:12 +0000] [11762] [INFO] Booting worker with pid: 11762
[2016-12-12 00:20:12 +0000] [11763] [INFO] Booting worker with pid: 11763

此时,可以通过访问 http://127.0.0.1:8000 进行测试。


$curl http://127.0.0.1:8000
Hello World

参数说明

-w 参数用于指定处理HTTP请求的worker进程数量。以下两种启动方式在效果上是等价的:


gunicorn -w 4 myapp:app
gunicorn --workers=4 myapp:app

参考:


 -w INT, --workers INT
            The number of worker processes for handling requests.

问题:为何直接调用 http://ip:8000 无法访问?这涉及什么请求机制?

默认情况下,Gunicorn带有 -b 参数,具体参考如下说明:


 -b ADDRESS, --bind ADDRESS
            The socket to bind. [['127.0.0.1:8000']]

采用以下方式启动,即可支持通过IP地址进行访问:


sudo gunicorn -w 2 -b 0.0.0.0:4000 myapp:app

示例代码2

之前使用的简单Flask方法如下:


from flask import Flask
app = Flask(__name__)

@app.route('/hello.world')
def check():
  return 'hello world!'


if __name__ == '__main__':
  app.run()

启动


$sudo gunicorn -b 0.0.0.0:300 -w 4 myapp3:app
[2016-12-18 19:19:51 +0000] [21005] [INFO] Starting gunicorn 19.6.0
[2016-12-18 19:19:51 +0000] [21005] [INFO] Listening at: http://0.0.0.0:300 (21005)
[2016-12-18 19:19:51 +0000] [21005] [INFO] Using worker: sync
[2016-12-18 19:19:51 +0000] [21010] [INFO] Booting worker with pid: 21010
[2016-12-18 19:19:51 +0000] [21011] [INFO] Booting worker with pid: 21011
[2016-12-18 19:19:51 +0000] [21014] [INFO] Booting worker with pid: 21014
[2016-12-18 19:19:51 +0000] [21017] [INFO] Booting worker with pid: 21017

测试


$curl localhost:300/hello.world
hello world!

启动异常


[ERROR] Connection in use: ('127.0.0.1', 8000)

导致启动失败的原因之一是之前启动的进程未被彻底终止。

注:Ctrl+Z 用于挂起进程,但并未终止它;而 Ctrl+C 则是终止进程。

如果使用了 Ctrl+Z 将进程挂起,之后想回到该进程可使用 fg 命令,随后通过 Ctrl+C 来关闭进程。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表