如何部署你的python web應用(二)

weixin_34320159發表於2016-11-13

How to Deploy Python WSGI Applications Using uWSGI Web Server with Nginx

uWSGI廣泛的功能、相對容易的配置使其成為許多部署需求的極佳選擇——尤其是與Nginx結合時。
Nginx + uWSGI + Flask/Django 的架構兼具效能與擴充性。以下簡潔地給出了能使用的uWSGI和Nginx的配置示例。以一個wsgi.py代表應用介面(Django或Flask)。詳細的還是推薦深入閱讀官方文件

安裝

sudo apt-get    update
sudo apt-get -y upgrade #更新
sudo apt-get -y install python3-dev
sudo apt-get -y install python3-pip
sudo pip3 install virtualenv
mkdir my_app
cd my_app
virtualenv my_app_venv
mkdir app
source my_app_venv/bin/activate
sudo pip3 install uwsgi
sudo apt-get install nginx
sudo service nginx start # 啟動nginx
# sudo service nginx stop # 暫停nginx
# sudo service nginx restart # 重啟nginx
touch wsgi.py

How To Install nginx on Ubuntu 12.04 LTS

檔案結構

my_app              # 包含所有東西的主資料夾
  |
  |=== my_app_venv  # python虛擬環境
  |=== app          # app應用
  |
  |--- wsgi.py      # 包含可呼叫的 application 的檔案
  |..
  |.
  • wsgi.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

配置uWSGI

  • 我們可以直接令uWSGI
uwsgi --socket 127.0.0.1:8080 --protocol http --wsgi-file wsgi.py

或者

uwsgi --http :8080 --wsgi-file wsgi.py

使用http協議繫結偵聽8080埠呼叫wsgi.py中的application,不需要額外的東西就行,它已經相當穩定和高效能,不過一般我們傾向於使用一個完全功能的web伺服器,如Nginx。

  • 此外,更普遍的做法是建立一個.ini配置檔案而不是以命令列引數的形式啟動uWSGI。使用uwsgi yourfile.ini命令執行

Web應用程式的示例配置:

[uwsgi]
# -------------
# 設定規則:
# key = value
# 註釋 : #
# -------------

socket = 127.0.0.1:8080
# bind to the specified UNIX/TCP socket using default protocol
# 繫結埠。預設情況下,uWSGI使用它自己的uwsgi協議,使用protocol引數修改 。

chdir  = /my_app
# 轉移到wsgi.py所在目錄,app根目錄

wsgi-file = wsgi.py
# pass requests to your WSGI application
# 將請求傳遞給你的WSGI應用
# 或者使用 module = [wsgi_module_name]:[application_callable_name]
# 如 module = wsgi:application

master=true
# a master process (will respawn your processes when they die) 
# 擁有一個主程式(會在程式死亡時重新啟動程式)

processes = 4
threads = 2
# spawn 4 processes (each with 2 threads)
# 產生4個程式(每個包含2個執行緒)

stats = 127.0.0.1:9191
# 狀態檢測埠
# Make some request to your app and then telnet to the port 9191, you’ll get lots of fun information.You may want to use “uwsgitop” (just pip install it), which is a top-like tool for monitoring instances.

max-requests = 1001
# 如果你擔心記憶體洩漏,並且不能想到一個更加堅實的處理它的方法,這個選項將允許你在處理設定的請求數量後自動重啟你的程式。

procname = My Application
# 設定程式名稱

更詳細的配置參看
uWSGI Quickstart for Python/WSGI applications
How to use Django with uWSGI
Starting your app with uwsgi - Flask

使用Nginx做反向代理

  • 典型架構
Client Request ----> Nginx (Reverse-Proxy)
                        |
                       /|\                           
                      | | `-> App. Server I.   127.0.0.1:8081  <--> Application
                      |  `--> App. Server II.  127.0.0.1:8082  <--> Application
                       `----> App. Server III. 127.0.0.1:8083  <--> Application

注意: 當應用程式被設定為在127.0.0.1上偵聽傳入連線時,只能在本地訪問它。如果使用0.0.0.0,它會也接受來自外部的連線。

  • Nginx配置
sudo gedit /etc/nginx/nginx.conf
# 配置完成後重啟服務
sudo service nginx stop
sudo service nginx start

Web應用程式的示例配置:

worker_processes 1;

events {

    worker_connections 1024;

}

http {

    sendfile on;

    gzip              on;
    gzip_http_version 1.0;
    gzip_proxied      any;
    gzip_min_length   500;
    gzip_disable      "MSIE [1-6]\.";
    gzip_types        text/plain text/xml text/css
                      text/comma-separated-values
                      text/javascript
                      application/x-javascript
                      application/atom+xml;

    # Configuration containing list of application servers
    upstream uwsgicluster {

        server 127.0.0.1:8080;
        # server 127.0.0.1:8081;
        # ..
        # .

    }

    # Configuration for Nginx
    server {

        # Running port
        listen 80;

        # Settings to by-pass for static files 
        location ^~ /static/  {

            # Example:
            # root /full/path/to/application/static/file/dir;
            root /app/static/;

        }

        # Serve a static file (ex. favico) outside static dir.
        location = /favico.ico  {

            root /app/favico.ico;

        }

        # Proxying connections to application servers
        location / {

            include            uwsgi_params;
            uwsgi_pass         uwsgicluster;

            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;

        }
    }
}

Creating an SSL certificate on Nginx.
How to Configure Nginx Web Server on a VPS.


其它連結

騰訊雲配置:Flask+uWSGI+Nginx
阿里雲部署 Flask + WSGI + Nginx 詳解

相關文章