djangoをnginx+gunicornで動かす。テキトー。

install

pip install gunicorn

sudo aptitude install nginx
cd /etc/nginx
sudo mv nginx.conf nginx.conf.orig
sudo vi nginx.conf

nginx.confを以下のように

## worker=1, port=8000
user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    accept_mutex off;
    # multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type application/octet-stream    ;
    access_log  /var/log/nginx/access.log combined;
    sendfile        on;

    upstream app_server {
        #server unix:/tmp/gunicorn.sock fail_timeout=0;
        # For a TCP configuration:
         server 127.0.0.1:8000 fail_timeout=0;
    }

    server {
        listen 80 default;
        client_max_body_size 4G;
        server_name _;

        keepalive_timeout 5;

     	# location /site_media/  {
		# 	root /PATH/TO/DJANGO/PROJECT;
		# }
        location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;

           # if (!-f $request_filename) {
           #     proxy_pass http://app_server;
           #     break;
           # }
        }
	
    }
}

概略。

  1. コメントされているsite_mediaの部分は、適切に設定する必要がある。画像ファイルとかのために。
  2. 404とかのlocation設定してない。
  3. 80 -> 8000 にforwarding
  4. walkerはひとつ

起動

sudo nginx -t 
sudo /etc/init.d/nginx restart

django

とても簡単。

  1. settings.pyのINSTALLED_APPSにgunicornを追加。
  2. runserverの代わりにrun_gunicornを使う。
# python manage.py runserver ##これは違う。
python manage.py run_gunicorn

追記

nginxとgunicornが同じホスト上にあるならunixのsocketを使っても良いかもしれない。

こう変える。

    upstream app_server {
        server unix:/tmp/django.sock fail_timeout=0;
        # For a TCP configuration:
        # server 127.0.0.1:8000 fail_timeout=0;
    }

djangoを起動させるときに、socketのアドレスを指定する。

python manage.py run_gunicorn --bind=unix:/tmp/django.sock