FastAPI项目部署--nginx+gunicorn部署

  在之前的分享中,FastAPI入门教程(持续更新中)的文章分享了Fastapi框架的入门和项目的实战,分享后,没有进行过部署,那么如何部署呢,今天带领大家去看下。

        部署选择了通用的nginx 和gunicorn来进行部署。如何部署呢,本篇带着大家去看一看。

        一、 环境安装

            安装nginx

     

brew install nginx  #mac部署
apt install nginx #linux部署
在windows可以执行下载安装

下载地址
http://nginx.org/en/download.html

  

安装后,修改下配置

在/usr/local/etc/nginx修改下配置
server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }

  启动nginx

  访问localhost

 

 

  这样代表我们的nginx配置完成

 安装gunicorn

        直接使用pip 安装即可

         pip install gunicorn

二、配置

        创建一个新的nginx.conf,配置下

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
server {
        listen 81;
        server_name localhost;
        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;

        }
    }
}

 配置后,指向了本地的8000端口,配置后。

            在去创建一个gunicorn.py

            代码如下如下

daemon=True #是否守护
bind='0.0.0.0:8000'#绑定
pidfile='gunicorn.pid'#pid文件地址
chdir='.' # 项目地址
worker_class='uvicorn.workers.UvicornWorker'
workers=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 = "gunicorn_access.log"
errorlog = "gunicorn_error.log"

    然后执行

三、启动配置

        启动gunicorn

gunicorn main:app -c gunicorn.py

 

        可以查看gunicorn是否启动,

        mac或者linx用

       

ps -ef | grep gunicorn

 

        windows 可以在对应的进程查看。

        启动nginx

nginx -c ./nginx.conf

        -c 后面跟着的是配置的地址,启动后,访问 81 可以正常访问,

        直接访问对应的接口文档地址

 

    这样就部署完成了。

    

posted @ 2022-08-27 14:30  北漂的雷子  阅读(4528)  评论(0编辑  收藏  举报