FastAPI 生产部署

开发部署

安装asgi插件

pipenv install uvicorn

# main.py

from fastapi import FastApi

app=FastApi()


@app.get('/hello')
async def hello():
    return {'message':'hello World'}


nvicorn main:app --reload 开发模式下运行 热加载

生产环境部署 CentOS8.x +Nginx

安装插件 pipenv install gunicorn

shell中执行gunicorn -v有版本输出表示安装成功

# 编写配置文件 gunicorn.py

daemon=True
bind='0.0.0.0:8000'
pidfile='/var/run/gunicorn.pid'
chdir='/opt/web/fastapi' # 工作目录
worker_class='uvicorn.workers.UvicornWorker'
workers=1  #multiprocessing.cpu_count()+1
threads=2
loglevel='debug' # 日志级别
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
accesslog = "/opt/web/fastapi/gunicorn_access.log" 
errorlog = "/opt/web/fastapi/gunicorn_error.log" 

gunicorn main:app -c gunicorn.py

在gunicorn_error.log  文件中看到日志输出表示启动成功

配置 gunicorn.service服务开机自启动

cat >/usr/lib/systemd/system/gunicorn.service << EOF
[Unit]
Description=Gunicorn fast
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking

PIDFile=/var/run/gunicorn.pid
ExecStart=/root/.local/share/virtualenvs/fastapi-Xq8atoqR/bin/gunicorn  -c 
/opt/web/fastapi/gunicorn.py main:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

EOF

systemctl daemon-reload

systemctl enable gunicorn

systemctl start gunicorn

查看服务状态

 systemctl status gunicorn

配置nginx代理访问

server {
        listen 80;
        server_name api.rainbow.cn;
        access_log  /var/log/nginx/access.log;
     
        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

nginx -s reload

 完成FastApi的生产部署

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恒云客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值