Nginx + Gunicorn + Django 部署web服务,nginxgunicorn


 1. 安装nginx
    #yum install nginx

 2. 修改nginx配置文件
    #vim /etc/nginx/nginx.conf
worker_processes  1;

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


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

     upstream cjogs_server {
        # fail_timeout=0 means we always retry an upstream even if it failed
        # to return a good HTTP response

        # for UNIX domain socket setups
       # fail_timeout=0 means we always retry an upstream even if it failed
        # to return a good HTTP response

        # for UNIX domain socket setups
        server unix:/var/run/gunicorn.sock fail_timeout=0; # 设置gunicorn sock文件路径

        # for a TCP configuration
        # server 192.168.0.7:8000 fail_timeout=0;
    }

    server {
        listen   8888;  # 设置端口号
        server_name 127.0.0.1;   # 设置服务器IP

        client_max_body_size 4G;

        access_log /var/log/nginx/test-access.log; 设置日志文件路径
        error_log /var/log/nginx/test-error.log;

        location /static/ {
            alias   /data/apps/test/static/; 设置静态文件路径
        }

        location /media/ {
            alias   /data/apps/test/media/;
        }

        location / {
            # an HTTP header important enough to have its own Wikipedia entry:
            #   http://en.wikipedia.org/wiki/X-Forwarded-For
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            # enable this if and only if you use HTTPS, this helps Rack
            # set the proper protocol for doing redirects:
            # proxy_set_header X-Forwarded-Proto https;

            # pass the Host: header from the client right along so redirects
            # can be set properly within the Rack application
            proxy_set_header Host $http_host;

            # we don't want nginx trying to do something clever with
            # redirects, we set the Host: header above already.
            proxy_redirect off;

             # set "proxy_buffering off" *only* for Rainbows! when doing
            # Comet/long-poll stuff.  It's also safe to set if you're
            # using only serving fast clients with Unicorn + nginx.
            # Otherwise you _want_ nginx to buffer responses to slow
            # clients, really.
            # proxy_buffering off;

            # Try to serve static files from nginx, no point in making an
            # *application* server like Unicorn/Rainbows! serve static files.
            if (!-f $request_filename) {
                proxy_pass http://test_server;
                break;
            }
        }
    }
}
3. 安装 gunicron
     # pip install gunicorn

4. 编写服务脚本,并保存到/etc/init.d/目录下命名为mywebserver
#!/bin/bash
#
# GUNICORN        Startup script for gunicorn
#


# Source function library.
. /etc/rc.d/init.d/functions

if [ -L $0 ]; then
    initscript=`/bin/readlink -f $0`
else
    initscript=$0
fi

sysconfig=`/bin/basename $initscript`

if [ -f /etc/sysconfig/$sysconfig ]; then
    . /etc/sysconfig/$sysconfig
fi

DJANGO_WSGI_MODULE=test.wsgi
PYTHON_VENV="/data/tools/test"  # python 虚拟环境
DJANGODIR="/data/apps/test"     # django项目路径

gunicorn=${GUNICORN-${PYTHON_VENV}/bin/gunicorn}
pidfile='/var/run/test-pid'
sockfile='/var/run/gunicorn.sock'   # 设置gunicorn sock文件路径
prog=`/bin/basename $gunicorn`

start() {
    # cd ${DJANGODIR}
    source ${PYTHON_VENV}/bin/activate

    export DJANGO_SETTINGS_MODULE=test.settings
    export PYTHONPATH=${DJANGODIR}

    exec ${gunicorn} ${DJANGO_WSGI_MODULE}:application \
            --daemon \
            --pid $pidfile \
            --name test \
            --workers 10 \
            --user=root --group=root \
            --bind=unix:$sockfile \
            --log-level=debug \
            --chdir=${DJANGODIR}  \    # django项目settings.py路径
            --log-file="/var/log/test-web.log" \
            --error-logfile="/var/log/test-web_error.log" \
            --access-logfile="/var/log/test-web_access.log" \
            --capture-output

    RETVAL=$?
    echo
    [ $RETVAL = 0 ]
    return $RETVAL   
}



stop() {
    echo -n $"Stopping $prog: "
    killproc -p ${pidfile} ${prog}
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f  ${pidfile}
}

rh_status() {
    status -p ${pidfile} ${gunicorn}
}

# See how we were called.
case "$1" in
    start)
        rh_status >/dev/null 2>&1 && exit 0
        start
        ;;
    stop)
        stop
        ;;
    status)
        rh_status
        RETVAL=$?
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo $"Usage: $prog {start|stop|restart|status|help}"
        RETVAL=2
esac

exit $RETVAL
 5. 启动Nginx服务(需要确保端口号未被占用)
    # service nginx restart

 6. 启动gunicorn服务
    # service mywebserver start

 注: 如果网页打开找不到静态文静路径,django项目的settings.py文件配置如下:
...
STATIC_ROOT = str(ROOT_DIR('staticfiles'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
    str(APPS_DIR.path('static')),
)

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# MEDIA CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR('media'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'

# URL Configuration
# ------------------------------------------------------------------------------
ROOT_URLCONF = 'config.urls'

# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = 'config.wsgi.application'
...

相关内容

    暂无相关文章