设置 Flask 应用程序 uWGSI Nginx - 服务器配置锅炉模板(默认代理和缓存)

这是来自 DigitalOcean 的如何在 Ubuntu 14.04 上使用 uWSGI 和 Nginx 服务 Flask 应用程序 的教程的移植 **

和 nginx 服务器的一些有用的 git 资源。

Flask 应用

本教程假设你使用 Ubuntu。

  1. 找到 var/www/文件夹。
  2. 创建你的 Web 应用程序文件夹 mkdir myexample
  3. cd myexample

可选你可能希望设置虚拟环境以在生产服务器上部署 Web 应用程序。

sudo pip install virtualenv

安装虚拟环境。

virtualenv myexample

为你的应用设置虚拟环境。

source myprojectenv/bin/activate 

激活你的环境。在这里,你将安装所有 python 包。

结束可选但推荐

设置 Flask 和网关 uWSGI

安装 flask 和 uSWGI 网关:

pip install uwsgi flask

myexample.py 中的 Flask 应用示例:

from flask import Flask
application = Flask(__name__)

@application.route("/")
def hello():
    return "<h1>Hello World</h1>"

if __name__ == "__main__":
    application.run(host='0.0.0.0')

创建文件以在你的 Web 应用程序和 Web 服务器之间进行通信:网关接口[ https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface]

nano wsgi.py

然后导入你的 webapp 模块并使其从网关入口点运行。

from myexample import application

if __name__ == "__main__":
    application.run()

测试 uWSGI:

uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi

要配置 uWSGI:

  1. 创建配置文件 .ini

    nano myexample.ini

  2. 网关 uWSGI 的基本配置

# include header for using uwsgi
[uwsgi]
# point it to your python module wsgi.py
module = wsgi
# tell uWSGI to start a master node to serve requests
master = true
# spawn number of processes handling requests
processes = 5
# use a Unix socket to communicate with Nginx. Nginx will pass connections to uWSGI through a socket, instead of using ports. This is preferable because Nginx and uWSGI stays on the same machine.
socket = myexample.sock
# ensure file permission on socket to be readable and writable
chmod-socket = 660
# clean the socket when processes stop
vacuum = true
# use die-on-term to communicate with Ubuntu versions using Upstart initialisations: see:
# http://uwsgi-docs.readthedocs.io/en/latest/Upstart.html?highlight=die%20on%20term
die-on-term = true

如果你使用的是虚拟环境,则可选择你可以使用虚拟环境。

Nginx 配置我们将使用 nginx:

  1. 默认服务器使用 uwsgi 协议将请求传递给套接字
  2. 默认服务器前的代理服务器
  3. 缓存服务器以缓存成功的请求(例如,你可能希望缓存 GET 请求,如果你的 Web 应用程序)

找到 sites-available 目录并为你的应用程序创建配置文件:

sudo nano /etc/nginx/sites-available/myexample

添加以下块,在注释中它的作用:

server {
   

    # setting up default server listening to port 80
    listen 8000 default_server;
    server_name myexample.com; #you can also use your IP 
    
    # specify charset encoding, optional
    charset utf-8;

    # specify root of your folder directory
    root /var/www/myexample;

    # specify locations for your web apps.
    # here using /api endpoint as example
    location /api {
        # include parameters of wsgi.py and pass them to socket
        include uwsgi_params;
        uwsgi_pass unix:/var/www/myexample/myexample.sock;
    }

}

# Here you will specify caching zones that will be used by your virtual server
# Cache will be stored in /tmp/nginx folder
# ensure nginx have permissions to write and read there!
# See also:
# http://nginx.org/en/docs/http/ngx_http_proxy_module.html

proxy_cache_path /tmp/nginx levels=1:2 keys_zone=my_zone:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

# set up the virtual host!
server {
    listen   80  default_server;
    
    # Now www.example.com will listen to port 80 and pass request to http://example.com
    server_name www.example.com;

    # Why not caching responses

    location /api {
        # set up headers for caching
        add_header X-Proxy-Cache $upstream_cache_status;

        # use zone specified above
        proxy_cache my_zone;
        proxy_cache_use_stale updating;
        proxy_cache_lock on;
        
        # cache all responses ?
        # proxy_cache_valid 30d;

        # better cache only 200 responses :)
        proxy_cache_valid 200 30d;

        # ignore headers to make cache expire
        proxy_ignore_headers X-Accel-Expires Expires Cache-Control;

        # pass requests to default server on port 8000
        proxy_pass http://example.com:8000/api;
    }
}

最后,将文件链接到 sites-enabled 目录。有关可用站点和已启用站点的说明,请参阅答案:[ http://serverfault.com/a/527644]

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

你现在已经完成了 nginx。但是,你可能想要查看这个非常珍贵的锅炉模板:[ https://github.com/h5bp/server-configs-nginx]

对微调非常有用。

现在测试 Nginx:

sudo nginx -t

启动 Nginx:

sudo service nginx restart

自动化 Ubuntu 启动 uWSGI 最后一件事是让 Ubuntu 启动 wsgi 网关与你的应用程序通信,否则你应该手动完成。

  1. 在 Ubuntu 中找到初始化脚本的目录,并创建一个新脚本:

sudo nano /etc/init/myexample.conf

  1. 添加以下块,在线注释以解释它的作用

    # description for the purpose of this script
    description "uWSGI server instance configured to serve myproject"
    
    # Tell to start on system runtime 2, 3, 4, 5. Stop at any other level (0,1,6). 
    # Linux run levels: [http://www.debianadmin.com/debian-and-ubuntu-linux-run-levels.html]
    start on runlevel [2345]
    stop on runlevel [!2345]
    
    # Set up permissions! "User" will be the username of your user account on ubuntu.
    setuid user
    # Allow www-data group to read and write from the socket file. 
    # www-data is normally the group Nginx and your web applications belong to.
    # you may have all web application projects under /var/www/ that belongs to www-data group
    setgid www-data
    
    # tell Ubunutu which environment to use.
    # This is the path of your virtual environment: python will be in this path if you installed virtualenv. Otherwise, use path of your python installation
    env PATH=/var/www/myexample/myexample/bin
    # then tell to Ubuntu to change and locate your web application directory
    chdir /var/www/myexample
    # finally execute initialisation script, that load your web app myexample.py
    exec uwsgi --ini myexample.ini
    

现在你可以激活你的脚本:sudo start myexample