天天看點

Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

環境

  1. ubuntu 18.04
  2. python3.6.7
  3. Django 2.1
  4. uWSGI 2.0.17.1
  5. Nginx 1.14.2

準備

使用 

virtualenvwrapper

 建立一個環境

$ mkvirtualenv django2
           

安裝和使用 

virtualenvwrapper

 參考 https://blog.csdn.net/weixin_38417098/article/details/86004118

安裝 Django

1. 切換環境

[email protected]:~$ workon django2
           

2. 安裝

(django2)[email protected]:~$ pip install  django==2.1
           

3. 測試

檢視版本

(django2) [email protected]:~$ python -m django --version
           

建立簡單項目

(django2) [email protected]:~$ django-admin startproject mysite
(django2) [email protected]:~$ cd mysite
(django2) [email protected]:~$ python manage.py runserver 0.0.0.0:8000
           
  1. 将已經完成開發的Django項目 mysite(mysite是Django項目名)拷貝到伺服器,
  2. 這裡拷貝到了 adamstream 使用者( adamstream 是伺服器可登入使用者名)路徑下,
  3. 最後相對路徑是

    ~/www/mysite

    ,絕對路徑是

    /home/adamstream/www/mysite

  4. 進入以上目錄,使用Django的内置伺服器測試看看 mysite 項目是否運作正常。
    [email protected]:~$ python manage.py runserver 127.0.0.1:8080
               

在浏覽器内輸入:http://127.0.0.1:8000,檢查django是否運作正常。

Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

安裝 uWSGI

1. 下載下傳安裝

[email protected]:~$ pip3 install uwsgi
           

2. 測試

檢視版本

[email protected]:~$ uwsgi --version
           

~/www/mysite

目錄中建立一個測試用的Python檔案

foobar.py

[email protected]:~$ touch foobar.py
           

foobar.py

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]
           

在 HTTP 端口 9090 部署

[email protected]:~$ uwsgi --http :9090 --wsgi-file foobar.py 
           
# 參數說明
--http:        指定IP 端口
--wsgi-file:   指向具體Python檔案
           

在浏覽器内輸入:http://127.0.0.1:9090,檢視是否有"Hello World"輸出

Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

安裝 Nginx

1. 安裝依賴庫

1. 安裝 gcc 依賴庫

Nginx是C語言開發,需要gcc依賴庫

先檢查本機是否有gcc環境

[email protected]:~$ gcc -v
           

如果沒有gcc環境,則需要安裝

[email protected]:~$ sudo apt install gcc
           

2. 安裝 pcre 依賴庫

  1. PCRE(Perl Compatible Regular Expressions) 是一個Perl庫,包括 perl 相容的正規表達式庫。
  2. nginx 的 http 子產品使用 pcre 來解析正規表達式,是以需要在 linux 上安裝 pcre 庫。
  3. pcre-devel 是使用 pcre 開發的一個二次開發庫。
[email protected]:~$ sudo apt install libpcre3 libpcre3-dev
           

檢視pcre版本

[email protected]:~$ pcre-config --version
           

3.安裝 zlib 依賴庫

  1. zlib 庫提供了很多種壓縮和解壓縮的方式。
  2. nginx 使用 zlib 對 http 包的内容進行 gzip 。
[email protected]:~$ sudo apt install zlib1g-dev
           

4.安裝 ssl 依賴庫

  1. OpenSSL 是一個強大的安全套接字層密碼庫,囊括主要的密碼算法、常用的密鑰和證書封裝管理功能及 SSL 協定,并提供豐富的應用程式供測試或其它目的使用。
  2. nginx 不僅支援 http 協定,還支援 https(即在ssl協定上傳輸http),是以需要安裝 OpenSSL 庫。
[email protected]:~$ sudo apt install openssl
           

2. 安裝Nginx

1. 下載下傳Nginx最新版本

http://nginx.org/en/download.html

Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

圖中左邊的Linux版本的tar.gz包,右邊為Windows版本

2.下載下傳到本地後解壓

[email protected]:~/下載下傳$ tar -zxvf nginx-1.14.2.tar.gz
           

3. 進入解壓目錄

[email protected]:~/下載下傳$ cd nginx-1.14.2
           

4. 配置

不需要去配置相關東西,預設就可以了,預設會安裝在 /usr/local/nginx

[email protected]:~/下載下傳/nginx-1.14.2$ ./configure
           

5. 編譯

6. 安裝

7. 啟動服務

查找安裝路徑

[email protected]:~$ whereis nginx
           

啟動服務

[email protected]:~$ cd /usr/local/nginx/sbin
[email protected]:~/usr/local/nginx/sbin$ sudo ./nginx
           

檢視Nginx程序

[email protected]:~/usr/local/nginx/sbin$ ps -ef|grep nginx
           

在浏覽器内輸入:http://localhost:8080,檢查 Nginx 是否運作正常

Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

*8. 将nginx添加到環境變量中(還是不要配置好)

[email protected]:~$ sudo vim /etc/profile
           

profile

最後添加語句

讀取配置

[email protected]:~$ source /etc/profile
           

測試啟動

[email protected]:~$ nginx  
2019/01/26 23:50:01 [warn] 13601#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /usr/local/nginx/conf/nginx.conf:2
2019/01/26 23:50:01 [emerg] 13601#0: open() "/usr/local/nginx/logs/nginx_error.log" failed (13: Permission denied)
           

無法啟動,原因是nginx中大部分的檔案隻有root使用者才能寫入,是以配置是無法起效的

9. Nginx常見指令

[email protected]:~$ nginx            # 啟動 Nginx
[email protected]:~$ nginx -s stop    # 停止 Nginx,待nginx程序處理任務完畢進行停止
[email protected]:~$ nginx -s quit    # 停止 Nginx,先查出nginx程序id再使用kill指令強制殺掉程序
[email protected]:~$ nginx -s reload  # 重新載入配置檔案
[email protected]:~$ nginx -s reopen  # 重新開機 Nginx
# -s 都是采用向 Nginx 發送信号的方式
           

10. 配置

建立 Nginx 運作的使用者

[email protected]:~$ /usr/sbin/groupadd www
[email protected]:~$ /usr/sbin/useradd -g www www
           

配置

nginx.conf

(/usr/local/nginx/conf/nginx.conf)

user  www www;
# 設定值和CPU核心數量一緻
worker_processes  4;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
# 日志位置和日志級别
error_log  /usr/local/nginx/logs/nginx_error.log crit;

#pid        logs/nginx.pid;

# 指定此程序可以打開的最大檔案描述符的值
worker_rlimit_nofile  65535;


events {
    # worker_connections  1024;
    use  epoll;
    worker_connections  65535;
}


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;
    
    client_header_buffer_size      32k;
    client_max_body_size           8m;
    large_client_header_buffers    4 32k;
    server_names_hash_bucket_size  128;

    sendfile  on;
    
    tcp_nopush   on;
    tcp_nodelay  on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    
    fastcgi_buffers            4 64k;
    fastcgi_buffer_size        64k;
    fastcgi_busy_buffers_size  128k;
    
    fastcgi_connect_timeout  300;
    fastcgi_read_timeout     300;
    fastcgi_send_timeout     300;
    

    gzip               on;
    gzip_buffers       4 16k;
    gzip_comp_level    2;
    gzip_http_version  1.0;
    gzip_min_length    1k;
    gzip_types         text/plain application/x-javascript text/css application/xml;
    gzip_vary          on;

    # server 虛拟主機的配置
    server {
        listen       80;         # 監聽端口
        server_name  localhost;  # 域名
        
        index  index.html index.htm index.php;
        root   /usr/local/nginx/html;  # 站點目錄

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        access_log off;

        location / {
            root   html;
            index  index.html index.htm;
            
            include  uwsgi_params;
            uwsgi_pass  192.168.31.93:8080;             //必須和uwsgi中的設定一緻
            uwsgi_param UWSGI_SCRIPT mysite.wsgi; //入口檔案,即wsgi.py相對于項目根目錄的位置,“.”相當于一層目錄
            uwsgi_param UWSGI_CHDIR ~/mysite;      //項目根目錄
            index  index.html index.htm;
            client_max_body_size 35m;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        
        location ~ .*\.(php|php5)?$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
         }
         
         location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
             expires 30d;
         }
         
         location ~ .*\.(js|css)?$ {
             expires 15d;
         }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
           

基于 uWSGI + Django 的實作

1. uWSGI 指令啟動 Django

1. 進入項目

[email protected]:~$ cd wwww/mysite
# db.sqlite3
# manage.py
# mysite
# polls
# static
           

2. 啟動項目

  1. 這裡依然使用HTTP協定,
  2. 指向Django項目的

    --file

    --module

    參數,
  3. 參數的值

    mysite.wsgi

    指向

    ~/www/mysite/mysite/wsgi.py

    子產品,
  4. 如果正常可以在浏覽器http://192.168.31.93:8080端口打開了項目
[email protected]:~/wwww/mysite$ uwsgi --http 192.168.31.93:8080 --file mysite/wsgi.py --static-map=/static=static
           

[email protected]:~/wwww/mysite$ uwsgi --http 192.168.31.93:8080 --module mysite.wsgi --static-map=/static=static
           
Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx
# 參數說明
--http:    指定IP 端口

# mysite/wsgi.py檔案裡有一個反射,如果你在調用他的時候沒有指定,Web Server就使用預設的
--file:    檔案形式調用
--module:  子產品形式調用

--static:  做一個映射,指定靜态檔案
           

2. uWSGI 配置檔案啟動 Django

  1. 對于uWSGI伺服器的配置,

    uwsgi

    指令加上很多

    --http

    ,

    --file

    ,

    --static

    等參數非常麻煩
  2. 可以寫成配置檔案的方式

1. 建立配置檔案

~/www/script

(django項目同級目錄建立script目錄)中建立一個配置檔案

uwsgi.ini

,用于存放配置腳本

[email protected]:~$ cd ~/www
[email protected]:~/www$ mkdir script
[email protected]:~/www/script$ cd script
adam[email protected]:~/www/script$ touch uwsgi.ini
           

uwsgi.ini

# uwsig使用配置檔案啟動
[uwsgi]
# 指定虛拟環境
virtualenv=/home/adamstream/.virtualenvs/django2
# 項目目錄
chdir=/home/adamstream/www/mysite
# 指定項目的application
module=mysite.wsgi:application
# 指定sock的檔案路徑,sock是套接字檔案
socket=/home/adamstream/www/script/uwsgi.sock
# 程序個數
workers=4
pidfile=/home/adamstream/www/script/uwsgi.pid
# 指定IP端口
http=192.168.31.93:8080
# 指定靜态檔案
static-map=/static=/home/adamstream/www/mysite/static
# 啟動uwsgi的使用者名和使用者組
uid=root
gid=root
# 啟用主程序
master=true
# 自動移除unix Socket和pid檔案當服務停止的時候
vacuum=true
# 序列化接受的内容,如果可能的話
thunder-lock=true
# 啟用線程
enable-threads=true
# 設定自中斷時間
harakiri=30
# 設定緩沖
post-buffering=4096
# 設定日志目錄
daemonize=/home/adamstream/www/script/uwsgi.log
           

2. 啟動項目

[email protected]:~$ uwsgi --ini ~/www/script/uwsgi.ini
           
Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

Django + Uwsgi + Nginx

1. 更改

wsgi.ini

~/www/script/wsgi.ini

# uwsig使用配置檔案啟動
[uwsgi]
# 指定虛拟環境
#virtualenv=/home/adamstream/.virtualenvs/django2
# 項目目錄
chdir=/home/adamstream/www/mysite
# 指定項目的application
module=mysite.wsgi:application
# 指定sock的檔案路徑
#socket=192.168.31.93:8080
socket=/home/adamstream/www/script/uwsgi.sock

###########################################################
# http參數用于以上測試,而與Nginx互動需要使用socket參數,
# 即使用TCP協定,WSGI和uwsgi協定都在TCP協定之上。
# socket參數也可以配置為網絡位址,如socket=192.168.31.93:8080,
# 但如果Nginx和uWSGI同在一個伺服器上,可以使用socket檔案的形式。
###########################################################

# 動态配置socket檔案的權限,因為socket檔案會在每次uWSGI啟動時被重新建立
chmod-socket=664
stats=192.168.31.93:9090
# 程序個數
workers=4
pidfile=/home/adamstream/www/script/uwsgi.pid
# 指定IP端口
#http=192.168.31.93:8080
# 指定靜态檔案
static-map=/static=/home/adamstream/www/mysite/static
# 啟動uwsgi的使用者名和使用者組
uid=root
gid=root
# 啟用主程序
master=true
# 自動移除unix Socket和pid檔案當服務停止的時候
vacuum=true
# 序列化接受的内容,如果可能的話
thunder-lock=true
# 啟用線程
enable-threads=true
# 設定自中斷時間
harakiri=30
# 設定緩沖
post-buffering=4096
# 設定日志目錄
daemonize=/home/adamstream/www/script/uwsgi.log
           

注意:

/home/adamstream/www/script/uwsgi.sock

檔案新建立的使用者www,無法寫入,需要改變檔案權限

# uwsgi.sock檔案屬性
# srw-rw-r-- 1 adamstream adamstream     0 1月  25 17:05 uwsgi.sock=
[email protected]:~/www/scrip$ sudo chmod o+w uwsgi.sock
           

但這個操作隻是在目前終端上起效,關閉此終端或重新登陸後,就要再執行此次操作。

2. 更改

nginx.conf

usr/local/nginx/conf/nginx.conf

...
http {
    ...

    # server 虛拟主機的配置
    server {
        listen       80;       # 監聽端口
        server_name  "192.168.31.93";  # 域名
        
        index  index.html index.htm index.php;
        #root   /usr/local/nginx/html;  # 站點目錄

        charset utf-8;

        gzip_types text/plain application/x-javascript text/css text/javascript application/x-httpd-php application/json text/json image/jpeg image/gif image/png application/octet-stream; # 支援壓縮的類型

        #access_log  logs/host.access.log  main;
        access_log off;

        # 指定項目路徑 uWSGI
        # location 相當于 Django 的 url(r'^admin/', admin.site.urls)
        location / {
            include  uwsgi_params;  # 導入一個 Nginx 子產品,用來和 uWSGI 進行通訊

            uwsgi_connect_timeout  30;  # 設定連接配接 uWSGI 的逾時時間
            uwsgi_pass  unix:///home/adamstream/www/script/uwsgi.sock;  # 指定 uWSGI 的 sock 檔案,所有動态請求就會直接丢給他
            #uwsgi_pass  192.168.31.93:8080;
            #uwsgi_param UWSGI_SCRIPT mysite.wsgi;
            #uwsgi_param UWSGI_CHDIR /home/adamstream/www/mysite;
            #index  index.html index.htm;
            #client_max_body_size 35m;
        }
        ...
    }
}
           

3. 開始測試

1. 首先啟動uWSGI

[email protected]:~$ uwsgi --ini ~/www/script/uwsgi.ini
[uWSGI] getting INI configuration from /home/adamstream/www/script/uwsgi.ini
[uwsgi-static] added mapping for /static => /home/adamstream/www/mysite/static
           

2. 然後啟動Nginx

[email protected]:~$ sudo /usr/local/nginx/sbin/nginx
           

3. 通路網站

在浏覽器輸入http://192.168.31:93

Django+Nginx+uWSGI部署環境準備安裝 Django安裝 uWSGI安裝 Nginx基于 uWSGI + Django 的實作Django + Uwsgi + Nginx

繼續閱讀