计划背景
零碎版本:debian9
环境搭配:python3
虚拟环境 + fastapi
+ uvicorn
+ gunicorn
我的项目根目录: /data/wwwroot/domian.com
官网文档中是以 IP:PORT
模式启动 fastapi
,但每次都要进虚拟环境通过命令启动 gunicorn
,贼麻烦。起初改成 systemd
+ gunicorn
的形式后,开机主动启动 gunicorn
而且不占用端口。
具体部署 fastapi
另外写文章阐明,本文章只说 nginx
+ systemd
+ gunicorn
的配置形式。
大略计划
新建以下文件:
/etc/systemd/system/gunicorn.service/etc/systemd/system/gunicorn.socket
nginx
的 conf
文件中 不必代理 ip:prot
模式,而是代理sock
文件。
具体步骤
/etc/systemd/system/gunicorn.service
:
[Unit]Description=gunicorn daemonRequires=gunicorn.socketAfter=network.target[Service]Type=notify# the specific user that our service will run asUser=gunicornGroup=www# another option for an even more restricted service is# DynamicUser=yes# see http://0pointer.net/blog/dynamic-users-with-systemd.htmlRuntimeDirectory=gunicorn# WorkingDirectory 是我的项目门路目录WorkingDirectory=/data/wwwroot/domian.com# 代替手动执行的命令,# 本来在虚拟环境中要执行的 gunicorn -c gconfig.py main:app -k uvicorn.workers.UvicornWorker# 其中 gunicorn 和 gconfig.py 要写残缺的门路名称ExecStart=/data/wwwroot/luejiao.com/venv/bin/gunicorn -c /data/wwwroot/luejiao.com/gconfig.py main:app -k uvicorn.workers.UvicornWorkerExecReload=/bin/kill -s HUP $MAINPIDKillMode=mixedTimeoutStopSec=5PrivateTmp=true[Install]WantedBy=multi-user.target
/etc/systemd/system/gunicorn.socket
:
[Unit]Description=gunicorn socket[Socket]# ListenStream 写要生成的 sock 文件门路,要写残缺门路。我是放到我的项目根目录下的。ListenStream=/data/wwwroot/domian.com/domian.com_gunicorn.sock# Our service won't need permissions for the socket, since it# inherits the file descriptor by socket activation# only the nginx daemon will need access to the socketUser=www-data# Optionally restrict the socket permissions even more.# Mode=600[Install]WantedBy=sockets.target
nginx
的 domian.conf
,其它配置不写,次要是 /
代理这部分:
location / { # 放弃原始 ip 端口模式,改为代理到 sock 文件 # proxy_pass http://127.0.0.1:3002; # unix 前面的门路就是后面文件中的 sock 文件的残缺门路,留神格局。 proxy_pass http://unix:/data/wwwroot/domian.com/domian.com_gunicorn.sock; }
操作命令
重启 nginx
后,会主动生成 domian_gunicorn.sock
,而后关上域名确认 fastapi
利用是否失常启动:
systemctl reload nginx.servicesystemctl restart nginx.service
开机启动并立刻启动 gonicorn.socket
:
systemctl enable gunicorn.socket --now
不同的操作命令:
启动: systemctl start gunicorn.service状态:systemctl status gunicorn.service进行:systemctl stop gunicorn.service重启:systemctl restart gunicorn.service