1. 程式人生 > 實用技巧 >django部署

django部署

django部署

採用 nginx + gunicorn + django部署,系統是centos7

安裝環境

  • nginx 安裝

    1. 官網下載安裝http://nginx.org/en/docs/

    2. 配置檔案

      user  root;
      worker_processes  1;
      events {
          worker_connections  1024;
      }
      http {
          include       mime.types;
          default_type  application/octet-stream;
          sendfile        on;
          server {
              listen 80;
              server_name  youtubemp4.us;
              charset utf-8;
              client_max_body_size 10m;
              access_log  /var/log/nginx/build-access.log;
              error_log  /var/log/nginx/build-err.log;
              location /static/ {
                  #靜態檔案如js,css的存放目錄
                  alias /root/en7/static/;
              }
              location / {
                  proxy_pass http://0.0.0.0:8000; # 這裡要配合啟動檔案使用
                  proxy_set_header   Host                 $http_host;
                  proxy_set_header   X-Real-IP            $remote_addr;
                  proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
                  proxy_set_header   X-Forwarded-Proto    $scheme;
              }
          }
      }
      
    3. 軟連線

      ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx

    4. 命令

      nginx -c xxx.conf
      nginx -s reload
      
  • gunicorn

    1. 安裝

    pip install gunicorn

    1. 配置檔案

      # /usr/bin/python3
      # encoding: utf-8
      import multiprocessing
      bind = '0.0.0.0:8000'      #繫結ip和埠號
      backlog = 512                #監聽佇列
      chdir = '/root/en7'  #gunicorn要切換到的目的工作目錄
      timeout = 30      #超時
      
      workers = multiprocessing.cpu_count() * 2 + 1    #程序數
      threads = 2 #指定每個程序開啟的執行緒數
      # 設定守護程序
      daemon = True
      
    2. 命令

      gunicorn 模組名.wsgi:application -c xxx.conf
      kill -9 pid
      
  • django

    1. 修改settings檔案

      DEBUG = False
      ALLOWED_HOSTS = ["149.28.39.105","youtubemp4.us"]
      STATIC_ROOT = os.path.join(BASE_DIR, 'static')
      
      # STATICFILES_DIRS = [
      #     os.path.join(BASE_DIR,"static")
      # ]
      
    2. 執行收集靜態檔案

      python manager.py collectstatic
      

部署步驟

拉取django專案

gunicorn啟動django專案

啟動nginx伺服器