django應用的部署

這裏分享下對django應用的部署方式,採用 django + gunicorn + nginx 部署應用。html

1.應用清單python

python2.7mysql

Django-1.8.7nginx

gunicorn-19.4.5sql

nginx數據庫

2.提早的準備django

因爲如今大多數服務器都是centos6的操做系統,系統自帶的python版本爲2.6,而Django1.8須要python2.7版本以上,因此要對python作升級。另外django和gunicorn用下載後的安裝包安裝的話,須要提早安裝一些包,不一樣的環境可能會不同,如下能夠作參考。我這裏的這個環境沒法連互聯網,因此安裝包等都是下載下來,拷貝進來的。推薦用virtualenv來安裝環境,這樣作最好了。centos

zlib-1.2.3-29.el6.x86_64 ##不然影響django安裝瀏覽器

zlib-devel-1.2.3-29.el6.x86_64 ##不然影響django安裝服務器

python-setuptools-0.6.10-3.el6.noarch ##不然影響django安裝

mysql-devel-5.1.73-5.el6_6.x86_64 ##若是django使用mysql的須要安裝不然django導入不了MysqlDB 模塊

mysql-libs-5.1.73-5.el6_6.x86_64 ##若是django使用mysql的須要安裝不然django導入不了MysqlDB 模塊

python-backports-1.0-5.el6.x86_64 ##安裝gunicorn須要不然gunicorn導入不了_ssl 模塊

python-backports-ssl_match_hostname-3.4.0.2-2.el6.noarch ##安裝gunicorn須要不然gunicorn導入不了_ssl 模塊

準備好後,將django 和 gunicorn 解包後 python setup.py install 安裝便可

nginx 能夠從官方網站 http://nginx.org/packages/centos/6/x86_64/RPMS/ 下載rpm包安裝

將應用經過SVN或GIT更新,而且修改好setting.py配置文件中的信息,譬如調整數據庫的位置。

而後驗證下django項目 python manage.py runserver 0.0.0.0:8000 啓動看看,沒問題就關閉。

3.配置靜態頁面

在開發過程當中靜態頁面是配置在django服務中static目錄下的,然而在部署生產環境時並不須要由django來作這種工做,由nginx來完成更好

在django中能夠在setting.py中的STATIC_ROOT定義靜態文件存放的位置,而STATIC_URL配置不用變.

故在setting.py中設置

STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR,'../static')) 即在上級目錄static中存放django中定義的靜態文件

執行命令 python manage.py collectstatic 就把靜態文件都部署到指定STATIC_ROOT下了

!!!注意static目錄與其上級目錄要有可讀權限,由於在後面的nginx配置須要,否則html頁面中會引用不到靜態文件報403 forbidden。

4.啓動gunicorn

cd 到django項目主目錄 dj是主目錄 wsgi是其中wsgi.py文件 application爲其中函數 -b參數後跟監聽IP地址和端口

執行命令 nohup /usr/local/python2.7/bin/gunicorn -b0.0.0.0:8999 dj.wsgi:application &

[2016-02-24 14:58:57 +0000] [20088] [INFO] Starting gunicorn 19.4.5

[2016-02-24 14:58:57 +0000] [20088] [INFO] Listening at: http://0.0.0.0:8999 (20088)

[2016-02-24 14:58:57 +0000] [20088] [INFO] Using worker: sync

[2016-02-24 14:58:57 +0000] [20093] [INFO] Booting worker with pid: 20093

5.配置nginx

配置nginx文件

cd /etc/nginx/conf.d

cp default.conf default.conf.bak

vi dj.conf


#這裏/home/app/static 就是前面STATIC_ROOT指向的靜態文件存放的地址

server {

listen 80;

location /static {

alias /home/app/static;

}

location / {

#這裏建議用127.0.0.1替代localhost 否則nginx可能會報connect() failed (111: Connection refused) while connecting to upstream ……[::1] 錯

proxy_pass http://127.0.0.1:8999;

}

}

service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

service nginx start


最後瀏覽器訪問應用便可

相關文章
相關標籤/搜索