假設我們使用 Python Flask 框架寫了一個網站,現在要讓他可以在網頁上運行,我們會需要:
- 使用 Apache / Nginx 擇一做為反向代理伺服器:負責靜網頁與動態網頁請求和結果的回覆
- 使用 gunicorn / uWSGI 擇一做為 WSGI 伺服器:負責接收代理伺服器的請求後,轉發給 Flask 以及接收 Flask 返回信息轉發給 Nginx
- Flask 收到請求後處理數據並返回頁面給 uWSGI 伺服器。

Table
一. Flask 為什麼需要 gunicorn / uWSGI
首先我們先了解什麼是 gunicorn / uWSGI 與 WSGI 的關係:
▍什麼是 WSGI:
Between the server and the application, there may be one or more WSGI middleware components, which implement both sides of the API, typically in Python code.
https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface
WSGI 的縮寫是 (Python Web Server GateWay Interface),簡單來說是一種規範,僅用於 Python 語言,於 PEP 333 — Python Web Server Gateway Interface v1.0 | Python.org 被提出,來規範 Web Server 和 Web Application 之間如何溝通。
▍什麼是 gunicorn / uWSGI:
它們實現了 WSGI、uwsgi、http 等規範的 Web Server。用於接收前端伺服器轉發的動態請求並處理後發給 Web Application。
▍所以 Flask 為什麼需要 gunicorn / uWSGI?
因為 Nginx 沒辦法實現 WSGI 規範,所以如果不使用 WSGI Server (Gunicorn / uWSGI) 的話,將使用框架 (Django / Flask) 自帶的 WSGI Server,而這個 Server 基本上是用來測試環境使用,不適合正式環境下使用。
二. Flask 為什麼需要 Nginx
Nginx 可以提高 Web Server 性能 ( 例如:uWSGI 處理靜態檔案不如 Nginx) 以及使用 Nginx 有以下好處:
- 緩存:可以減少 response 的等待時間。如果網頁服務上有大量的靜態檔案(如:CSS、圖片檔、JS 檔案),設置 Cache 可以讓瀏覽器就會緩存這些文件,節省網路流量的費用,也可以讓使用者訪問網站會顯得更快。
- 靜態檔案
- 均衡負載
- 反向代理:就是當外部網絡對內部網絡器是不能直接訪問的,要通過一個代理伺服器才能進行訪問,而外部網絡看到的只是代理伺服器,反饋也是由代理伺服器返回的
最後~
▍回顧本篇文章:
- Flask 為什麼需要 gunicorn / uWSGI
- 什麼是 WSGI
- 什麼是 gunicorn / uWSGI
- Flask 為什麼需要 Nginx
▍本篇參考文章:
關於更多 Python Flask 教學的延伸閱讀:
▍關於 Flask 教學系列目錄:
▍其他 Flask 相關教學: