使用systemd 添加gunicorn service 文件

668 阅读1分钟
  1. install gunicorn in virtualenv
  2. try to launch the gunicorn command line to verify the service or command line works normally.
  3. write system service file
  4. debug the service file execstart command line

Example:

  1. write the api.py
from fastapi import FastAPI
import uvicorn


app = FastAPI()


@app.get('/')
def get_func():
    return {'text': "hello world!"}, 200
  1. create virtualenv
$ python3.9 -m venv venv
$ source venv/bin/activate
$ pip install gunicorn uvicorn uvloop httptools fastapi
  1. test if the gunicorn can work
$ gunicorn apifast:app -w 2 -k uvicorn.workers.UvicornWorker -b "0.0.0.0:9090"
  1. if step 3 can work, write a system servie file
$ cat /etc/systemd/system/apifast.service
[Unit]
Description=Gunicorn instance daemon to serve API
After=network.target

[Service]
User=swqa
Group=nginx
WorkingDirectory=/home/swqa/fastApi
Environment="PATH=/home/swqa/fastApi/apienv/bin"
ExecStart=/home/swqa/fastApi/apienv/bin/gunicorn apifast:app -w 4 -k uvicorn.workers.UvicornWorker -b "0.0.0.0:7000"

[Install]
WantedBy=multi-user.target
  1. debug systemd service file method
$ sudo runuser -l swqa -c "cd /home/swqa/fastapi && PATH=/home/swqa/fastApi/apienv/bin gunicorn apifast:app -w 2 -k uvicorn.workers.UvicornWorker -b '0.0.0.0:7000'"

参考:containersolutions.github.io/runbooks/po… www.digitalocean.com/community/t…