要使用 Gunicorn 部署 Python 應用程序,您需要首先安裝 Gunicorn。在命令行中輸入以下命令以安裝 Gunicorn:
pip install gunicorn
安裝完成后,您可以使用以下步驟設置 Gunicorn:
打開終端或命令提示符。
導航到您的 Python 應用程序的根目錄。例如,如果您的應用程序位于 /home/user/myapp
,則輸入 cd /home/user/myapp
。
使用以下命令啟動 Gunicorn。將 <your_module>
替換為您的應用程序的主模塊(通常包含 wsgi.py
文件):
gunicorn <your_module>:application
例如,如果您的主模塊是 wsgi.py
,則命令如下:
gunicorn wsgi:application
-b
或 --bind
選項指定端口號。例如,要將端口更改為 8080,請輸入:gunicorn -b 0.0.0.0:8080 <your_module>:application
-w
或 --workers
選項指定工作進程的數量。例如,要使用 4 個工作進程,請輸入:gunicorn -w 4 <your_module>:application
-k
或 --threads
選項)或啟用訪問日志(使用 -l
或 --log-level
選項)。有關詳細信息和其他可用選項,請參閱 Gunicorn 文檔。注意:在生產環境中部署 Gunicorn 時,建議使用反向代理服務器(如 Nginx 或 Apache)與 Gunicorn 配合使用,以便更好地處理 SSL/TLS、負載均衡和其他高級功能。