在 macOS 上使用 Homebrew 安裝 Nginx,搭配 flup FastCGI 伺服器部署 Flask 應用。本文涵蓋 Nginx 安裝配置、FastCGI 啟動、Socket 權限問題排解、使用者/群組設定完整流程。
brew install nginx
# 配置檔:/usr/local/etc/nginx/nginx.conf
# 預設埠:8080
nginx # 啟動
訪問 https://localhost:8080 確認 Nginx 運作。
編輯 nginx.conf 的 server 區塊:
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
try_files $uri @flaskr;
}
location @flaskr {
include fastcgi_params;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param SCRIPT_NAME "";
fastcgi_pass unix:/tmp/flaskr-fcgi.sock;
}
}
重新載入:
nginx -s quit
sudo nginx # 埠 80 需 root
pip install flup
專案目錄建立 flaskr.fcgi:
#!/usr/bin/python
from flup.server.fcgi import WSGIServer
from flaskr import app
if __name__ == '__main__':
WSGIServer(app, bindAddress='/tmp/flaskr-fcgi.sock').run()
chmod +x flaskr.fcgi
# 方式一:screen 後台
screen
./flaskr.fcgi
# 方式二:nohup
nohup ./flaskr.fcgi &
首次啟動 Nginx 回傳 502,錯誤日誌顯示:
connect() to unix:/tmp/flaskr-fcgi.sock failed (13: Permission denied)
# nginx.conf 主區塊加入
user wzy wheel; # 使用者:群組
user 僅指定使用者時,Nginx 會嘗試同名群組(不存在則報錯)user 使用者 群組 避免錯誤wheel 為 macOS 管理員群組重新啟動 Nginx 後訪問 https://localhost 即可看到 Flask 應用。
Client → Nginx (Port 80) → FastCGI Socket → flup WSGIServer → Flask App
靜態檔案直接服務
supervisor 或 launchd 管理 FastCGI 進程