安裝
uwsgi有很多安裝方式,編譯安裝,pip ,系統包管理(apt,yum) 。
所有的服務器端軟件,無特殊需求,推薦以系統包管理(apt,yum)的方式安裝。以程序來使用的python模塊,諸如,salt,hg,supervisor 也推薦以系統包管理的方式安裝。以庫來使用的才用pip的方式安裝。
所以uwsgi的最好安裝方式是以包管理的方式安裝。
apt-get install uwsgi uwsgi-plugins-all
運行
uwsgi能部署所有wsgi程序。
我們有如下的一個 app.py
def application(environ, start_response):
status = '200 OK'
output = 'World!'
response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(12)]
write = start_response(status, response_headers)
write('Hello ')
return [output]
可以通過uwsgi直接運行
uwsgi -s 127.0.0.1:8080 -w app
在nginx我們這樣配置
server {
server_name example.com;
location / {
include uwsgi_params;
uwsgi_pass 192.168.1.201:8081;
}
}
這樣就完成了最簡單的部署。
舉個例子,我們通過uwsgi部署hg的web。我們假設hg倉庫的根目錄是/var/hg
新建hgweb.conf 這個和wsgi無關,是hg的web配置
[collections]
/var/hg = /var/hg
[web]
style = paper
allow_archive = gz, zip, bz2
baseurl = /
hidden = false
allow_read = *
allow_push = *
push_ssl = false
新建 hgweb.py
from mercurial import demandimport; demandimport.enable()
from mercurial.hgweb.hgwebdir_mod import hgwebdir
application = hgwebdir('/var/hg/hgweb.conf')
運行
uwsgi -s 127.0.0.1:8080 -w hgweb --daemonize /var/log/hgrepo.wsgi
其中參數-w是 hgweb.py –daemonzie 以守護進程啟動。
Django 的部署
對於流行的框架,uwsgi有特別的支持。下面是一個典型的uwsgi django運行命令
uwsgi --plugins python -s 127.0.0.1:8080 -M -p 8 -t 600 -R 2000 \
--virtualenv=/usr/local/python-env/django
--env DJANGO_SETTINGS_MODULE=settings \
-w "django.core.handlers.wsgi:WSGIHandler()" \
--daemonize django.wsgi --pidfile /var/run/django.pid
--touch-reload /var/run/django.pid
其中uwsgi提供了方便的virtualenv支持,能夠直接指定運行需要的virtualenv,對於多站點的部署隔離環境非常好用。touch-reload 提供了方便的重新載入方式。一般uwsgi啟動cpu核心倍數的進程,由-p指定。其他參數請參考uwsgi文檔。或 uwsgi -h 直接查看。
生產運營
在實際運營當中並不是直接部署就萬事大吉。要想提供穩定的服務還有很多監控和優化的工作需要做。
在每秒數百請求的壓力下,有可能面臨文件描述符不足。ubuntu server默認只有1024
ulimit -n 10240
在處理較費時的請求時,uwsgi隊列數可能面臨不足 添加–listen參數,該參數默認為100,可改為1024. 諸如此類的性能參數需要在運營中調整。