Ubuntu 14.04+Django 1.7.1+Nginx+uwsgi部署最簡記錄(精簡自uwsgi官網教程)

walterrwu發表於2014-11-18

Ubuntu 14.04 Python 2.7.6 Django 1.7.1 Virtualenv name:test Nginx uwsgi
假設 專案資料夾位於 /data/www/ts 設定儲存在 ./conf
virtualenv name = test
domain name = example.com

django+uwsgi的部署實在是太蛋疼了..網上已有的教程似乎有新版本的相容問題。最後跑到uwsgi官網上找的教程終於跑通了..
不過官網的教程似乎有引導教學性質,部署的時候就顯得很繞彎路,在這裡記錄下來精簡內容

http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html

~~首先,需要一個uwsgi_params檔案,放在專案的conf資料夾裡面。之後需要指向它。~~
官網給的自己寫一個params的檔案是沒有必要的,其他例子中都用這句代替: include uwsgi_params

建立一個叫做ts_nginx.conf 的檔案,內容如下

設定中沒有使用sockets作內部傳輸,因為測試沒成功..可能是許可權問題,日後搞明白了可以改一下.
location裡面官方給的例子是沒有root選項的,但是這會導致把埠改到80後無法替換掉nginx的預設首頁(這破事兒折騰我好幾個小時..)加上就好了.

# ts_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
    server 127.0.0.1:8001; # for a web port socket (we`ll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen 80;
    # the domain name it will serve for
    server_name .example.com; # substitute your machine`s IP address or FQDN
    charset utf-8;

    # max upload size
    client_max_body_size 75M; # adjust to taste

    # Django media
    location /media {
        alias /data/www/ts/media; # your Django project`s media files - amend as required
    }

    location /static {
        alias /data/www/ts/static; # your Django project`s static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        root /data/www/ts
        uwsgi_pass django;
        include uwsgi_params; # the uwsgi_params file you installed
    }
}

把這個conf檔案連線到nginx的搜尋目錄裡面。

sudo ln -s /data/www/ts/conf/ts_nginx.conf /etc/nginx/sites-enabled/
sudo ln -s /data/www/ts/conf/ts_nginx.conf /etc/nginx/sites-available/

第二行是我自己覺得應該加的..

先決條件:這裡要設定好django專案的settings裡面static files

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

and then run

python manage.py collectstatic

之後:

service nginx restart

應該就可以看到
http://example.cn:8000/media/1.gif
了(事先放進去一個靜態檔案)

之後的blabla步驟都是廢話(因為不用sockets),跳到這裡:

Configuring uWSGI to run with a .ini file

ts_uwsgi.ini 在專案根目錄

[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /data/www/ts
# Django`s wsgi file
module = ts.wsgi
# the virtualenv (full path)
home = /root/.envs/test
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = 127.0.0.1:8001
# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true
# set an environment variable
env = DJANGO_SETTINGS_MODULE=conf.settings 

uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

這裡環境變數設定env需要conf資料夾有init.py,否則conf不會被認為是module

專案目錄下的同名app目錄下的wsgi.py可以指定專案用uwsgi執行的settings檔案.(注意!)

相關文章