- install gunicorn in virtualenv
- try to launch the gunicorn command line to verify the service or command line works normally.
- write system service file
- debug the service file execstart command line
Example:
- write the api.py
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get('/')
def get_func():
return {'text': "hello world!"}, 200
- create virtualenv
$ python3.9 -m venv venv
$ source venv/bin/activate
$ pip install gunicorn uvicorn uvloop httptools fastapi
- test if the gunicorn can work
$ gunicorn apifast:app -w 2 -k uvicorn.workers.UvicornWorker -b "0.0.0.0:9090"
- 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
- 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…