1.  首页
  2.  博客
  3. django+gunicorn+nginx 配置

django+gunicorn+nginx 配置


折腾了好久 apache+wsgi 不知道为什么一直在 memory leak

在失去了改源码的激情中, 只能通过换服务的方式解决了.

借鉴 instagram 的典型架构使用

django + gunicorn + nginx 跑 app server 来支撑

安装 django 这里就不多说了....

gunicorn 安装其实也非常简单

懒的去折腾些什么了. 所以,直接用 apt-get 安装

aptitude install gunicorn

配置 gunicorn+django 的启动脚本

    #!/bin/bash
    set -e 
    LOGFILE=/tmp/guni.log
    LOGDIR=$(dirname $LOGFILE)
    NUM_WORKERS=3  # cpu core nums * 2 + 1
    USER=nobody
    GROUP=nogroup
    WORKER=gevent # install python gevent
    ADDRESS=127.0.0.1:8000
    cd /path/to/project/
    test -d $LOGDIR || mkdir -p $LOGDIR
    exec gunicorn_django -w $NUM_WORKERS --bind=$ADDRESS \
      -k $WORKER --daemon \
      --user=$USER --group=$GROUP --log-level=error \
      --log-file=$LOGFILE 2>>$LOGFILE

这样 gunicorn 就安装完成了.

接下来, 整合nginx. 同样,安装也不说了.

    user nobody nogroup;
    worker_processes  8;

    #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;
        accept_mutex on;
        use epoll;
    }


    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;
        tcp_nodelay     on;

        keepalive_timeout  5;

        gzip on;
        gzip_min_length  1100;
        gzip_buffers     4 32k;
        gzip_types       text/plain application/x-javascript text/xml text/css;

        upstream app_server_djangoapp {
            server 127.0.0.1:8000 fail_timeout=5;
        }

        server {
            listen       80;
            server_name  _;

            root /path/to/project;

            location /static/ {
            if ($query_string) {
            expires max;
    #       log_not_found off;
                 }
             }

        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_djangoapp;
                break;
            }
        }

            #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;
            }
        }
    }

先介绍到这里, 继续 debug.

参考文档: http://senko.net/en/django-nginx-gunicorn/

评论 0