How to set up Nginx+Gunicorn+Django(Python)


Nginx+Gunicorn+Django(Python)

When we have finished a project and going to delploy on the web, we might face the problem, how we are going to deploy. Here is my way to do it: Nginx+Gunicorn

Gunicorn is a kind of tool samialar with uWSGI but it's much more simple than uWSGI settiing.

Niginx setup

First you need to install the Niginx below is the niginx install command on centOS: yum install Niginx Waithing the install completed. Then we need to change the Nginx configure setting, normally it's under etc/Nginx/nginx.conf , after we opened it, we need to take a look where the configure file link the supported file:

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
    }

After we know the supported configure file, then we need to open the file and do the setting, below is what i have set on my server:

server {
        listen 80;
        server_name cngw.cf;
        server_name_in_redirect off;
        access_log /www/wwwroot/log/nginx.access.log;
        error_log /www/wwwroot/log/nginx.error.log;

        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_pass_header       Authorization;
            proxy_pass_header       WWW-Authenticate;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /static/ {
            alias /www/wwwroot/DjangoBlog/collectedstatic/;
        }
    }

Need to restar the service after all configure sudo service nginx restart

Gunicorn setup

Then we need to go to set up the gunicorn. Go to you project virtual enviroment to use pip install the gunicorn: pip install gunicorn After we have installed the gunicorn, we need to do some setting. In the project ettings.p INSTALLED_APPS add gunicorn:

INSTALLED_APPS = [
...
...
'gunicorn',
]

gunicorn.conf.py

import multiprocessing
bind = "127.0.0.1:8000"
workers = 2
errorlog = '/home/xxx/xxx/gunicorn.error.log'
accesslog = '/home/xxx/xxx/gunicorn.access.log'
loglevel = 'debug'
proc_name = 'gunicorn_project'

Start the project

Now we can start up the gunicorn: $ sudo nohup gunicorn 项目名.wsgi:application -c /home/xxx/xxx/gunicorn.conf.py&

Every thing is done, enjoy your project on web.

Original