部署

提要

nginx + gunicorn + flask的应用部署

  1. 挂载到子路径,gunicorn启动参数里设置 --env SCRIPT_NAME=/your_prefix 指定前缀
  2. nginx反向代理 location使用前述前缀,注意proxy_pass末尾不用添加反斜杠,透传全部路径uri, 关闭nginx的proxy_redirect
  3. systemd 服务文件守护进程

具体示例

gunicorn启动命令

1
gunicorn -w 1 -b 127.0.0.1:8000 --env SCRIPT_NAME=/example some.app:app

nginx反向代理

1
2
3
4
5
6
7
8
9
location /example/ {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Cookie $http_cookie;
proxy_redirect off;
}

服务文件

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=Gunicorn instance to serve my Flask app
After=network.target

[Service]
User=someone
Group=someone
WorkingDirectory=/home/someone/breaker
Environment="PATH=/home/someone/breaker/.venv/bin"
ExecStart=/home/someone/breaker/.venv/bin/gunicorn -w 2 -b 127.0.0.1:8000 --env SCRIPT_NAME=/example some.app:app

[Install]
WantedBy=multi-user.target