基於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虛擬環境

    由於我想用anaconda裝虛擬環境,所以我先裝了anaconda

    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,出現以下類似即成功,剩下的豐富web App就靠後續了
    在這裏插入圖片描述

    可以用ps aux | grep 8080命令查看哪個進程佔用8080端口

    reference:

    【gunicorn官網】

    【廖雪峯python網站】

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

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