Linux nginx+uWSGI+django+virtualenv+supervisor發佈web服務器

用Nginx+uwsgi緣由

首先nginx 是對外的服務接口,外部瀏覽器經過url訪問nginx,

2nginx 接收到瀏覽器發送過來的http請求,將包進行解析,分析url,若是是靜態文件請求就直接訪問用戶給nginx配置的靜態文件目錄,直接返回用戶請求的靜態文件,

若是不是靜態文件,而是一個動態的請求,那麼nginx就將請求轉發給uwsgi,uwsgi 接收到請求以後將包進行處理,處理成wsgi能夠接受的格式,併發給wsgi,wsgi 根據請求調用應用程序的某個文件,某個文件的某個函數,最後處理完將返回值再次交給wsgi,wsgi將返回值進行打包,打包成uwsgi可以接收的格式,uwsgi接收wsgi 發送的請求,並轉發給nginx,nginx最終將返回值返回給瀏覽器。

3要知道第一級的nginx並非必須的,uwsgi徹底能夠完成整個的和瀏覽器交互的流程,可是要考慮到某些狀況
安全問題,程序不能直接被瀏覽器訪問到,而是經過nginx,nginx只開放某個接口,uwsgi自己是內網接口,這樣運維人員在nginx上加上安全性的限制,能夠達到保護程序的做用。

2負載均衡問題,一個uwsgi極可能不夠用,即便開了多個work也是不行,畢竟一臺機器的cpu和內存都是有限的,有了nginx作代理,一個nginx能夠代理多臺uwsgi完成uwsgi的負載均衡。

3靜態文件問題,用django或是uwsgi這種東西來負責靜態文件的處理是很浪費的行爲,並且他們自己對文件的處理也不如nginx好,因此整個靜態文件的處理都直接由nginx完成,靜態文件的訪問徹底不去通過uwsgi以及其後面的東西。

爲何要用nginx,uwsgi
View Code

 

基礎開發環境配置

yum groupinstall "Development tools"
yum install zlib-devel bzip2-devel pcre-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel

 

python3 + virtualenv安裝

 

安裝django1.11

pip3 install django==1.11
#建立django項目mysite
django-admin startproject mysite
#建立app01
python3 manage.py startapp app01

mysite/settings.pyhtml

#settings.py設置
ALLOWED_HOSTS = ['*']
install app01

mysite/urls.pypython

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello_django/', views.hello),
]

app01/views.pynginx

from django.shortcuts import render,HttpResponse

# Create your views here.
def hello(request):
    print('request is :',request)
    return HttpResponse('django is ok ')

 

安裝uWSGI

進入虛擬環境venv,安裝uwsgi
(venv) [root@slave 192.168.11.64 /opt]$pip3 install uwsgi
檢查uwsgi版本
(venv) [root@slave 192.168.11.64 /opt]$uwsgi --version
2.0.17.1
#檢查uwsgi python版本
uwsgi --python-version

運行簡單的uWSGIsql

#啓動一個python
uwsgi --http :8000 --wsgi-file test.py
http :8000: 使用http協議,端口8000
wsgi-file test.py: 加載指定的文件,test.py
#test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"] # python3

uWsgi熱加載python程序

在啓動命令後面加上參數
uwsgi --http :8088 --module mysite.wsgi --py-autoreload=1 
#發佈命令
command= /home/venv/bin/uwsgi --uwsgi 0.0.0.0:8000 --chdir /opt/mysite --home=/home/venv --module mysite.wsgi
#此時修改django代碼,uWSGI會自動加載django程序,頁面生效

運行django程序apache

#mysite/wsgi.py  確保找到這個文件
uwsgi --http :8000 --module mysite.wsgi
module mysite.wsgi: 加載指定的wsgi模塊

uwsgi配置文件django

uwsgi支持ini、xml等多種配置方式,本文以 ini 爲例, 在/etc/目錄下新建uwsgi_nginx.ini,添加以下配置:

# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /opt/mysite
# Django's wsgi file
module          = mysite.wsgi
# the virtualenv (full path)
home            = /opt/venv
# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 1
# the socket (use the full path to be safe
socket          = 0.0.0.0:8000
# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true

uwsgi.ini

 

指定配置文件啓動命令

uwsgi --ini  /etc/uwsgi_nginx.ini

 

配置nginx結合uWSGI

配置nginx.conf瀏覽器

worker_processes  1;
error_log  logs/error.log;
pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  logs/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
  #nginx反向代理uwsgi
    server {
        listen       80;
        server_name  192.168.11.64;
        location / {
      #nginx自帶ngx_http_uwsgi_module模塊,起到nginx和uwsgi交互做用
         #經過uwsgi_pass設置服務器地址和協議,講動態請求轉發給uwsgi處理
         include  /opt/nginx1-12/conf/uwsgi_params;
         uwsgi_pass 0.0.0.0:8000;
            root   html;
            index  index.html index.htm;
        }
      #nginx處理靜態頁面資源
      location /static{
        alias /opt/nginx1-12/static;   
         }
     #nginx處理媒體資源
     location /media{
        alias /opt/nginx1-12/media;  
         }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

 

supervisor

supervisor 是基於 python 的任務管理工具,用來自動運行各類後臺任務,若是要重啓任務,每次都本身手動 kill 掉任務進程,這樣很繁瑣,並且一旦程序錯誤致使進程退出的話,系統也沒法自動重載任務。tomcat

因爲supervisor在python3下沒法使用,所以只能用python2去下載!安全

#注意此時已經退出虛擬環境了!
yum install python-setuptools
easy_install supervisor

經過命令生成supervisor的配支文件服務器

echo_supervisord_conf > /etc/supervisord.conf

而後再/etc/supervisord.conf末尾添加上以下代碼

supervisord.conf配置文件參數解釋
[program:xx]是被管理的進程配置參數,xx是進程的名稱
[program:xx]
command=/opt/apache-tomcat-8.0.35/bin/catalina.sh run  ; 程序啓動命令
autostart=true       ; 在supervisord啓動的時候也自動啓動
startsecs=10         ; 啓動10秒後沒有異常退出,就表示進程正常啓動了,默認爲1秒
autorestart=true     ; 程序退出後自動重啓,可選值:[unexpected,true,false],默認爲unexpected,表示進程意外殺死後才重啓
startretries=3       ; 啓動失敗自動重試次數,默認是3
user=tomcat          ; 用哪一個用戶啓動進程,默認是root
priority=999         ; 進程啓動優先級,默認999,值小的優先啓動
redirect_stderr=true ; 把stderr重定向到stdout,默認false
stdout_logfile_maxbytes=20MB  ; stdout 日誌文件大小,默認50MB
stdout_logfile_backups = 20   ; stdout 日誌文件備份數,默認是10
; stdout 日誌文件,須要注意當指定目錄不存在時沒法正常啓動,因此須要手動建立目錄(supervisord 會自動建立日誌文件)
stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out
stopasgroup=false     ;默認爲false,進程被殺死時,是否向這個進程組發送stop信號,包括子進程
killasgroup=false     ;默認爲false,向進程組發送kill信號,包括子進程
[program:my]
#command=/opt/venv/bin/uwsgi --ini  /etc/uwsgi_nginx.ini  #這裏是結合virtualenv的命令 和supervisor的精髓!!!!
command= /home/venv/bin/uwsgi --uwsgi 0.0.0.0:8000 --chdir /opt/mysite --home=/home/venv --module mysite.wsgi
#--home指的是虛擬環境目錄  --module找到 mysite/wsgi.py   

 

最後啓動supervisor,完成uWSGI啓動django,nginx反向代理

supervisord -c /etc/supervisord.conf #啓動supervisor
supervisorctl -c /etxc/supervisord.conf restart my  #重啓my項目
supervisorctl -c 
/etc/supervisord
.conf [start|stop|restart] [program-name|all]

 

從新加載supervisor

1、添加好配置文件後

2、更新新的配置到supervisord    

supervisorctl update
3、從新啓動配置中的全部程序

supervisorctl reload
4、啓動某個進程(program_name=你配置中寫的程序名稱)

supervisorctl start program_name
5、查看正在守候的進程

supervisorctl
6、中止某一進程 (program_name=你配置中寫的程序名稱)

pervisorctl stop program_name
7、重啓某一進程 (program_name=你配置中寫的程序名稱)

supervisorctl restart program_name
8、中止所有進程

supervisorctl stop all
注意:顯示用stop中止掉的進程,用reload或者update都不會自動重啓。

 

django的靜態文件與nginx配置

mysite/settings.py

STATIC_ROOT='/opt/nginx1-12/static'
STATIC_URL = '/static/'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,"static"),
]

參數STATIC_ROOT做用

經過python3 manage.py collectstatic 收集全部你使用的靜態文件保存到STATIC_ROOT!

STATIC_ROOT 文件夾 是用來將全部STATICFILES_DIRS中全部文件夾中的文件,以及各app中static中的文件都複製過來
# 把這些文件放到一塊兒是爲了用nginx等部署的時候更方便
相關文章
相關標籤/搜索