基于flask+gunicorn+nginx来部署web App

时间:2023-03-09 05:03:40
基于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后可以看到类似

基于flask+gunicorn+nginx来部署web App

  • 安装配置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,出现以下即可

    基于flask+gunicorn+nginx来部署web App

    reference:

    【gunicorn官网】

    【廖雪峰python网站】

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