FastAPI項目部署--nginx+gunicorn部署 FastAPI入門教程(持續更新中)

  在之前的分享中,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 可以正常訪問,

        直接訪問對應的接口文檔地址

 

    這樣就部署完成了。

    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章