Setting up Django with Nginx

Posted by Jeffery Yee | 12:16 AM

There are several ways to set up Django with Nginx.

1. usingfastcgi

This assumes you are using ubuntu 10.04 or later.
You'll need nginx and flup installed.
sudo aptitude install nginx python-flup
In your django project, start up fastcgi. See the fastcgi docs for more info.
python ./manage.py runfcgi host=127.0.0.1 port=8080
Next, we need to create a configuration file in /etc/nginx/sites-available/sample_project.conf and symlink it to /etc/nginx/sites-enabled/sample_project.conf:
sudo touch /etc/nginx/sites-available/sample_project.conf
sudo ln -s /etc/nginx/sites-available/sample_project.conf /etc/nginx/sites-enabled/sample_project.conf
Here is what a minimal conf file would look like:
server {
    listen 80;
    server_name myhostname.com;
    access_log /var/log/nginx/sample_project.access.log;
    error_log /var/log/nginx/sample_project.error.log;

    # https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-production
    location /static/ { # STATIC_URL
        alias /home/www/myhostname.com/static/; # STATIC_ROOT
        expires 30d;
    }

    location /media/ { # MEDIA_URL
        alias /home/www/myhostname/static/; # MEDIA_ROOT
        expires 30d;
    }

    location / {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:8080;
    }
}
Now, reload nginx.
sudo /etc/init.d/nginx reload
If your urls are not working correctly, you may need to add this line to location /:
    fastcgi_split_path_info ^()(.*)$;

2. Running the Django application with uswgi and nginx

a) install uSWGI

sudo pip install uwsgi

b) Create a file called test.py:

# test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return "Hello World"

c) Run uWSGI:

uwsgi --http :8000 --wsgi-file test.py
if everything is ok, you should be able to visit http://localhost:8000

d) Test you Django project, 

create a Django project named testdjango, then test it with the following:
python manage.py runserver 0.0.0.0:8000

e) Now create a file called mysite_nginx.conf, and put it in /etc/nginx/sites-enabled:

upstream django {
    server unix:///home/zheng/Downloads/testdjango/testdjango.sock; # for a fie 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;

    root /home/zheng/Downloads/testdjango;

    # the domain name it will serve for
    server_name djangouwsgi.info; # 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 /home/zheng/Downloads/testdjango/media;  # your Django project's media files - amend as required
    }

    location /static {
        alias /home/zheng/Downloads/testdjango/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /home/zheng/Downloads/testdjango/uwsgi_params; # the uwsgi_params file you installed
    }
}

f) start uwsgi process to server python

uwsgi --socket mysite.sock --wsgi-file testdjango/wsgi.py --chmod-socket=666 # (very permissive)

or Configuring uWSGI to run with a .ini file

We can put the same options that we used with uWSGI into a file, and then ask uWSGI to run with that file. It makes it easier to manage configurations.
Create a file called `mysite_uwsgi.ini`:
# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /path/to/your/project
# Django's wsgi file
module          = project.wsgi
# the virtualenv (full path)
home            = /path/to/virtualenv

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
socket          = /path/to/your/project/mysite.sock
# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true
And run uswgi using this file:
uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

Emperor mode

uWSGI can run in ‘emperor’ mode. In this mode it keeps an eye on a directory of uWSGI config files, and will spawn instances (‘vassals’) for each one it finds.
Whenever a config file is amended, the emperor will automatically restart the vassal.
# create a directory for the vassals
sudo mkdir /etc/uwsgi
sudo mkdir /etc/uwsgi/vassals
# symlink from the default config directory to your config file
sudo ln -s /path/to/your/mysite/mysite_uwsgi.ini /etc/uwsgi/vassals/
# run the emperor
uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data
You may need to run uWSGI with sudo:
sudo uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data
The options mean:
  • emperor: where to look for vassals (config files)
  • uid: the user id of the process once it’s started
  • gid: the group id of the process once it’s started
Check the site; it should be running.

Make uWSGI startup when the system boots

The last step is to make it all happen automatically at system startup time.
Edit /etc/rc.local and add:
/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data
before the line “exit 0”.
And that should be it!
Note:
During this process, you may encounter problems like I did, so you may be interesting to :

ImportError: No module named django.core.handlers.wsgi (Django on Nginx)

References:
https://uwsgi.readthedocs.org/en/latest/tutorials/Django_and_nginx.html

0 comments

Popular Posts

无觅相关文章插件,迅速提升网站流量