基於flask+gunicorn+nginx來部署web App


基於flask+gunicorn&&nginx來部署web App

WSGI協議

Web框架致力於如何生成HTML代碼,而Web服務器用於處理和響應HTTP請求。Web框架和Web服務器之間的通信,需要一套雙方都遵守的接口協議。WSGI協議就是用來統一這兩者的接口的。

WSGI容器——Gunicorn

常用的WSGI容器有Gunicorn和uWSGI,但Gunicorn直接用命令啟動,不需要編寫配置文件,相對uWSGI要容易很多,所以這里我也選擇用Gunicorn作為容器。

安裝環境

  • python虛擬環境

    wget https://repo.continuum.io/archive/Anaconda3-5.0.1-Linux-x86_64.sh
    bash Anaconda3-5.0.1-Linux-x86_64.sh
    
  • 建立虛擬環境並激活

    conda create -n flask python=3.6
    source activate flask
    
  • 安裝flask和gunicorn

    pip install flask 
    pip install gunicorn
    

    運行 Gunicorn

    (flask) $ gunicorn -w 4 -b 127.0.0.1:8080 test:app
    

    參數含義(具體參考官網https://docs.gunicorn.org/en/stable/run.html

    workers = 4
    bind = ‘127.0.0.1:8080’

    test是模塊名,app是flask對象

​ 舉個例子,新建test.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#test.py
from flask import Flask,request
app = Flask(__name__)
@app.route('/')
def home():
    return "yes,it works.I'm going to sleep"
if __name__ == '__main__':
    app.run(debug=False) 

運行gunicorn后可以看到類似
在這里插入圖片描述

  • 安裝配置nginx

    sudo apt-get update
    sudo apt-get install nginx
    

    直接進入 Nginx 的默認配置文件進行修改

    sudo gedit /etc/nginx/site-avalidable/default
    

    先備份一下 default 文件

    sudo cp /etc/nginx/site-avalidable/default /etc/nginx/site-avalidable/default.bak

    server {
        
        server_name  12.13.14.15; # 主機的域名,或者ip地址
        location / {
            proxy_pass http://127.0.0.1:8080; # 這里是指向 gunicorn host 的服務地址
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
      }
    

    修改之后需要重新起動 nginx 服務

    sudo /etc/init.d/nginx restart
    
  • 重新啟用一下gunicorn

    (flask) $ gunicorn -w 4 -b 127.0.0.1:8080 test:app
    

    在瀏覽器輸入服務器ip,出現以下即可
    在這里插入圖片描述

    reference:

    【gunicorn官網】

    【廖雪峰python網站】

    http://python.jobbole.com/87666/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM