通過gunicorn部署django項目,比使用uwsgi方式要簡單,具體操作如下:
步驟:
1. 安裝依賴
yum install python3
yum install nginx (或者下載nginx包部署)
yum install gunicorn
pip install gevent # 這個是gunicorn運行的一種模式
easy_install -U greenlet
easy_install -U eventlet
pip install gevent
2. 檢查python/nginx安裝是否成功
a. 輸入python3,是否出現交互命令頁面
b. 啟動nginx, 瀏覽器訪問ip,出現weclome ngix
舉例:
啟動nginx: ./nginx
2種方式驗證nginx是否啟動/安裝成功:
進程查看: ps -ef |grep nginx
頁面訪問:
3. gunicorn 簡單使用
按照上面的例子,當前目錄為 /home/myapp, myapp中有一個包 gunicorn_app,gunicorn_app.py代碼如下:
def app(environ, start_response):
data = b"Hello, World!\n"
start_response("200 OK", [("Content-Type", "text/plain"),("Content-Length", str(len(data)))])
return iter([data])
我們將要運行 test.py文件中的 app(當然名字由你決定,可以是myapp,demo等等)
gunicorn -w 2 gunicorn_app:app
上圖展示了兩個很重要的信息:


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; server_name 192.168.252.79; charset utf-8; #access_log logs/host.access.log main; location / { proxy_pass http://0.0.0.0:8001; # 這里要配合啟動文件使用 proxy_redirect off; 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; } location /static { alias /data/service/Django_project/static/; } #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 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; # } #} }
3. 加載靜態文件,具體步驟如下:
a. 修改settings.py中STATIC_ROOT為你的static靜態文件的物理路徑,比如說我靜態文件存放在/data/service/Django_project/static中,首先創建Django目錄下的static文件夾,最后修改settings.py中STATIC_ROOT指向/data/service/Django_project/static.
b. 運行python3 manage.py collectstatic命令,這將從Django資源包中復制必須的靜態文件到STATIC_ROOT指示的static文件夾中,這其中包括admin界面所必須的樣式表(style)、圖片(image)及腳本(js)等。
c.修改nginx配置文件, nginx.conf中指向static目錄。
4. Django根目錄創建 gunicorn.py文件,具體內容如下:
#gunicorn.py # coding:utf-8 import multiprocessing bind = '0.0.0.0:8001' #綁定ip和端口號 backlog = 512 #監聽隊列 chdir = '/data/service/Django_project' #gunicorn要切換到的目的工作目錄 timeout = 30 #超時 worker_class = 'gevent' #使用gevent模式,還可以使用sync 模式,默認的是sync模式 workers = multiprocessing.cpu_count() * 2 + 1 #進程數 threads = 2 #指定每個進程開啟的線程數 loglevel = 'info' #日志級別,這個日志級別指的是錯誤日志的級別,而訪問日志的級別無法設置 access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' #設置gunicorn訪問日志格式,錯誤日志無法設置 accesslog = "/home/gunicorn_log/gunicorn_access.log" #訪問日志文件 errorlog = "/home/gunicorn_log/gunicorn_error.log" #錯誤日志文件
5. 可以通過命令啟動服務,也可以指向腳本啟動服務
命令: /data/service/Django_project目錄下,執行 gunicorn Djanfo_project.wsgi -c gunicorn.py
腳本: 在/data/service/Django_project目錄,創建 restrt.sh, 具體內容如下: ./restart.sh start

#!/bin/sh ## service name #項目的目錄 SERVICE_DIR=/data/service/Django_project #gunicorn的名字 SERVICE_NAME=gunicorn #gunicorn的配置文件名 SERVICE_CONF=gunicon.py #pid存放的位置 PID=gunicorn\.pid export PATH=$PATH:$HOME/bin:/usr/local/python3/bin cd $SERVICE_DIR start(){ nohup gunicorn app_basic_info.wsgi -c $SERVICE_DIR/gunicorn.py>/dev/null 2>&1 & echo $! > $SERVICE_DIR/$PID echo "*** start $SERVICE_NAME ***" } stop(){ kill `cat $SERVICE_DIR/$PID` rm -rf $SERVICE_DIR/$PID echo "*** stop $SERVICE_NAME ***" sleep 2 P_ID=`ps -ef | grep -w "$SERVICE_NAME" | grep -v "grep" | awk '{print $2}'` if [ "$P_ID" == "" ]; then echo "*** $SERVICE_NAME process not exists or stop success ***" else echo "*** $SERVICE_NAME process pid is:$P_ID ***" echo "*** begin kill $SERVICE_NAME process,kill is:$P_ID ***" kill -9 $P_ID fi } f_usage() { echo "USAGE: restart [options]" echo "OPTIONS:" echo " start" echo " stop " echo " restart" } case "$1" in "start") start ;; "stop") stop ;; "restart") stop sleep 2 start echo "*** restart $SERVICE_NAME ***" ;; *) f_usage ;; esac exit 0
6. 瀏覽器訪問, http://localhost/admin/login