設定 Flask 應用程式 uWGSI Nginx - 伺服器配置鍋爐模板(預設代理和快取)
這是來自 DigitalOcean 的如何在 Ubuntu 14.04 上使用 uWSGI 和 Nginx 服務 Flask 應用程式 的教程的移植 **
和 nginx 伺服器的一些有用的 git 資源。
Flask 應用
本教程假設你使用 Ubuntu。
- 找到
var/www/
資料夾。 - 建立你的 Web 應用程式資料夾
mkdir myexample
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:
-
建立配置檔案
.ini
nano myexample.ini
-
閘道器 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:
- 預設伺服器使用 uwsgi 協議將請求傳遞給套接字
- 預設伺服器前的代理伺服器
- 快取伺服器以快取成功的請求(例如,你可能希望快取 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 閘道器與你的應用程式通訊,否則你應該手動完成。
- 在 Ubuntu 中找到初始化指令碼的目錄,並建立一個新指令碼:
sudo nano /etc/init/myexample.conf
-
新增以下塊,線上註釋以解釋它的作用
# 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