我们可以将我们的 Flask 应用程序直接连接到 Nginx 服务器吗?

Can we connect our Flask app directly with Nginx server?

我在 Internet 上找到了一些文章,讨论将像 "Nginx" 这样的重型 Web 服务器集成到 Flask 应用程序中,但是除了 Nginx,他们还借助 "Gunicorn" 网络服务器。

我的问题是,为什么有必要将 "Gunicorn" 网络服务器与 uWSGI 或 Nginx 一起使用?

您可以按照这些博客通过连接到 Nginx 进行部署

不使用Gunicorn,使用uwsgi过程变得复杂

https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04

https://vladikk.com/2013/09/12/serving-flask-with-nginx-on-ubuntu/

您需要了解什么是 Web 服务器网关接口 (WSGI) 才能了解 Gunicorn、uWSGI 和 Nginx 之间的区别。

这是什么意思?

[WSGI is] a proposed standard interface between web servers and Python web applications or frameworks, to promote web application portability across a variety of web servers. Source: PEP 333

如上所述,它是一种标准化,可简化服务器内 python 中 Web 应用程序的实施。 WSGI 描述了服务器和 python 应用程序之间必须如何交互。无论您的应用程序是什么,如果您遵循 PEP 333 中定义的规则,那么任何 WSGI-compatible HTTP 服务器都将能够与您的应用程序通信。

但是重新发明轮子是没有意义的,开发者已经创建了WSGI应用程序,让您可以更轻松地创建应用程序。 Flask 是其中之一,但还有其他的。

为什么我需要 WSGI HTTP 服务器?我可以在 cmd 中 运行 我的 Flask 应用程序,不是吗?

你总是需要一个 WSGI HTTP 服务器。 Flask 是一个非常好的工具,它直接包含一个 Werkzeug 开发服务器,但您一定不要在生产中使用 Werkzeug 服务器。

The [Werkzeug] development server is not intended to be used on production systems. It was designed especially for development purposes and performs poorly under high load. Source: Werkzeug Documentation

这就是为什么当您尝试使用命令 运行() 运行 您的烧瓶应用程序时总是收到此消息的原因。

WARNING: Do not use the development server in a production environment.

那么您将需要一台用于生产的服务器。

Gunicorn、uWSGI、Twisted Web 等?

有许多 WSGI-compatible 服务器可用。选择纯粹是任意的,完全取决于您的需要。安装和配置可能不同。更多或更少的选项将可用。由您决定哪一个最适合您。 Flask 文档中有一部分是为此保留的:Standalone WSGI Container.

这个 link 也可能有用:Flask Deploying

Nginx 的作用是什么?

Nginx 可以作为 reverse proxy.

A reverse proxy is an intermediary proxy service which takes a client request, passes it on to one or more servers, and subsequently delivers the server's response to the client. Source: Setting up an Nginx Reverse Proxy

更进一步

使用Nginx + WSGI服务器有什么优势? CI/CD.

dockerize Nginx 服务器和 WSGI 服务器中的应用程序真的很容易。然后您可以使用 Kubernetes 管理您的码头工人并管理与 Jenkins 的持续集成。 DevOps 文化。

但是,这绝对不是强制性的。一个也很好用的解决方案是 Nginx Unit,它让你拥有 Nginx 的强大功能,并与 Gunicorn 或 uWSGI 分道扬镳。在这个解决方案中可以找到的缺陷是它与 Docker + Kubernetes + Jenkins 时尚不兼容,您可以在 Google 上轻松找到。在上面做持续集成是很有可能的,但是不太常见。这将需要更多的知识:blue/green环境等....