1. 程式人生 > >Django專案部署(django+guncorn+virtualenv+nginx)

Django專案部署(django+guncorn+virtualenv+nginx)

 

一、說明

    為了django專案部署到生產環境上,能夠穩定的執行,且能夠同時指出http和https的訪問,對django的部署進行了一些研究,決定採用django + gunicorn + virtualenv +nginx + mysql的方式進行部署,下面是本次部署專案的目錄結構:

                         

 

二、虛擬包的製作

    本次部署是採用virtualenv方式的部署,考慮到可能在多臺機器上進行部署(例如:在多臺測試機器上部署),所以為了減少Python模組包的安裝,決定將虛擬環境打成包的形式,可以考到任意一臺環境上執行,避免了在每臺機器上都要安裝相應的模組包,一下是虛擬包的製作方法:

 

  • 首先在你的linux的伺服器上安裝python2.7, ./configure --prefix=/home/kxdqa/mock-server/py,然後執行make && make install 進行python的安裝
  • 安裝完python後,進行virtualenv的安裝
  • 然後建立你所需要的python的虛擬env環境,virtualenv -p /home/kxdqa/mock-server/py/bin/python2.7 /home/kxdqa/mock-server/myenv,myenv裡面會產生一個bin目錄和一個lib目錄,bin裡面有python,activate,easy_install,而且以後你要裝django,django-admin.py也會放到這裡,lib目錄下有site-package,裝的lib會放到這裡來.
  • 然後進入到虛擬環境myenv中,. bin/activate,進入虛擬環境展示如下:

    (myenv) [[email protected]_172_30_131_183 myenv]#

  • 然後在虛擬環境進行你所需要的模組包的安裝

  • 為了虛擬包可以在別的機器上依然可以執行,則需要修改bin/activate這個指令碼,找到設定VIRTUAL_ENV變亮的地方,改成如下: 

    export VIRTUAL_ENV=`pwd`

  • 本次的伺服器部署包,需要再安裝gunicorn,安裝方式可以採用pip或者原始碼安裝都行
  • 然後將myenv打包即可

三、django專案的配置

1.gunicorn的配置

  • 在當前的django專案下,新增gunicorn的 配置檔案gunicorn.conf.py,內容如下:
import multiprocessing

# 繫結ip和埠
bind = "0.0.0.0:8088"

# 用於處理工作程序的數量
workers = multiprocessing.cpu_count() * 2 + 1

# 錯誤日誌
errorlog = "/home/kxdqa/logic_mock/logs/gunicorn.error.log"

 

2.django靜態檔案的配置注:gunicorn的配置詳解見:點選開啟鏈

  • 在django專案的settings.py配置檔案中 ,新增STATIC_ROOT的配置,配置如下:
STATIC_ROOT = os.path.join(BASE_DIR, 'collect_static/')
  • 執行python manage.py collectstatic命令,就會將所有的靜態檔案複製一份到collect_static的資料夾下

 

3.嘗試啟動

gunicorn的啟動方式有兩種:

  • 使用配置檔案的方式:gunicorn logic_mock.wsgi:application -c /home/kxdqa/logic_mock/gunicorn.conf.py
  • 不使用配置檔案的方式:gunicorn logic_mock.wsgi:application -b 0.0.0.0:8088

guncorn的啟動後的關閉命令:ps aux | grep -Ei 'logic_mock.wsgi' | grep -v 'grep' |  awk '{print $2}' | xargs kill

四、Nginx的安裝

1.安裝

  • 安裝gcc編譯模組:yum install gcc
  • 安裝g++編譯模組:yum install gcc-c++ libstdc++-devel
  • 安裝nginx的依賴包:

    yum -y install pcre-devel      

    yum install -y zlib-devel    yum install -y openssl(安裝nginx報錯的,把這個裝上)

下載nginx的安裝包,進行安裝:

./configure--prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module       編譯安裝:make && make install

注:後面的 --with必須要有,不然nginx進行ssl設定的話,會出錯

驗證是否安裝成功:cd /usr/local/nginx/sbin/     . nginx  進行啟動(如果啟動失敗的話,檢視80埠是否被佔用)   然後到瀏覽器上輸入ip地址,看是否出現nginx的歡迎上,如果出現則安裝成功

2.nginx配置

 

  • 編寫nginx的啟動指令碼,將指令碼放到/etc/init.d下,指令碼如下:

   

#!/bin/bash
#nginx Startup script for the Nginx HTTP Server


# it is v.0.0.2 version.


# chkconfig: - 85 15


# description: Nginx is a high-performance web and proxy server.


#              It has a lot of features, but it's not for everyone.


# processname: nginx


# pidfile: /var/run/nginx.pid


# config: /usr/local/nginx/conf/nginx.conf


nginxd=/usr/local/nginx/sbin/nginx


nginx_config=/usr/local/nginx/conf/nginx.conf


nginx_pid=/var/run/nginx.pid


RETVAL=0


prog="nginx"


# Source function library.


. /etc/rc.d/init.d/functions


# Source networking configuration.


. /etc/sysconfig/network


# Check that networking is up.


[ ${NETWORKING} = "no" ] && exit 0


[ -x $nginxd ] || exit 0


# Start nginx daemons functions.


start() {


if [ -e $nginx_pid ];then


   echo "nginx already running...."


   exit 1


fi


   echo -n $"Starting $prog: "


   daemon $nginxd -c ${nginx_config}


   RETVAL=$?


   echo


   [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx


   return $RETVAL


}


# Stop nginx daemons functions.


stop() {


        echo -n $"Stopping $prog: "


        killproc $nginxd


        RETVAL=$?


        echo


        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid


}


# reload nginx service functions.


reload() {


    echo -n $"Reloading $prog: "


    #kill -HUP `cat ${nginx_pid}`


    killproc $nginxd -HUP


    RETVAL=$?


    echo


}


# See how we were called.


case "$1" in


start)


        start


        ;;


stop)


        stop


        ;;


reload)


        reload


        ;;


restart)


        stop


        start


        ;;


status)


        status $prog


        RETVAL=$?


        ;;


*)


        echo $"Usage: $prog {start|stop|restart|reload|status|help}"


        exit 1


esac


exit $RETVAL
nginx啟動指令碼
  • 執行如下命令,新增到服務中:
chkconfig --add /etc/init.d/nginx

chmod 755 /etc/init.d/nginx

chkconfig --add nginx

至此,nginx安裝成功

 
nginx啟動、停止、無間斷服務重啟,可選  start | stop | restart | reload | status |  help

service nginx start  啟動

servie nginx stop   停止

service nginx help 幫助
  • 對nginx配置django專案,配置檔案nginx.conf如下:
    user  root;
    worker_processes  1;
    
    
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    
    
    #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;
        #tcp_nopush     on;
    
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
    
        #gzip  on;
    
    
        server {
            listen      80 default backlog=2048;
    listen      443 ssl;
            server_name localhost;
    access_log /home/kxdqa/logic_mock/logs/nginx_access.log;
    error_log /home/kxdqa/logic_mock/logs/nginx_error.log;
    charset utf-8;
    
    
    ssl_certificate         /home/kxdqa/logic_mock/cert/logic_server.crt;
    ssl_certificate_key     /home/kxdqa/logic_mock/cert/logic_server.key;
    
    #ssl_protocols          SSLv2 SSLv3 TLSv1.2;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;
    ssl_prefer_server_ciphers  on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    #ssl_session_timeout   5m; 
    #index index.html index.htm
    
    
            #charset koi8-r;
    
    
            #access_log  logs/host.access.log  main;
            #
            location / {
       #proxy_redirect off;
                proxy_pass http://127.0.0.1:8088;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
    
    location ~ ^/(media|static) {
       root /home/kxdqa/logic_mock;
       expires 30d;
    }
    
    
            #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;
            }
    
    
            # 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;
        #    server_name  localhost;
    
    
        #    ssl                  on;
        #    ssl_certificate      cert.pem;
        #    ssl_certificate_key  cert.key;
    
    
        #    ssl_session_timeout  5m;
    
    
        #    ssl_protocols  SSLv2 SSLv3 TLSv1;
        #    ssl_ciphers  HIGH:!aNULL:!MD5;
        #    ssl_prefer_server_ciphers   on;
    
    
        #    location / {
        #        root   html;
        #        index  index.html index.htm;
        #    }
        #}
    
    
    }
    nginx.conf的配置

 

至此,django專案安裝完成,一次啟動nginx和gunicorn即可(如果需要使用https,則需要在目錄結構的certs目錄下,新增ssl證書,然後在nginx中改變證書的名字,重啟nginx即可)