nginx+gunicorn+fastapi 部署自動後臺啓動

方案背景

系統版本:debian9
環境搭配:python3 虛擬環境 + fastapi + uvicorn + gunicorn
項目根目錄: /data/wwwroot/domian.comhtml

官方文檔中是以 IP:PORT 形式啓動 fastapi,但每次都要進虛擬環境經過命令啓動 gunicorn,賊麻煩。後來改爲 systemd + gunicorn 的方式後,開機自動啓動 gunicorn 並且不佔用端口。python

具體部署 fastapi 另外寫文章說明,本文章只說 nginx + systemd + gunicorn 的配置方式。nginx

大概方案

新建如下文件:api

/etc/systemd/system/gunicorn.service
/etc/systemd/system/gunicorn.socket

nginxconf 文件中 不用代理 ip:prot 形式,而是代理sock 文件。app

具體步驟

/etc/systemd/system/gunicorn.servicedom

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
Type=notify
# the specific user that our service will run as
User=gunicorn
Group=www
# another option for an even more restricted service is
# DynamicUser=yes
# see http://0pointer.net/blog/dynamic-users-with-systemd.html
RuntimeDirectory=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.UvicornWorker
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target

/etc/systemd/system/gunicorn.socketsocket

[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 socket
User=www-data
# Optionally restrict the socket permissions even more.
# Mode=600

[Install]
WantedBy=sockets.target

nginxdomian.conf,其它配置不寫,主要是 / 代理這部分:ui

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 應用是否正常啓動:.net

systemctl reload nginx.service
systemctl 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
相關文章
相關標籤/搜索