Friday 27 November 2015

Configuring Django with uWSGI + NGINX Server

Before you start setting up uWSGI :
 

1. Make sure you are in a virtualenv for the software we need to install.Create Virtualenv like this:
       
        virtualenv uwsgi-tutorial
        cd uwsgi-tutorial
        source bin/activate

2. Install Django into your virtualenv, create a new project, and cd into the project:
       
      pip install Django
      django-admin.py startproject mysite
      cd mysite
       
 <-- Basic uWSGI installation and configuration -->
    

3. Install uWSGI into your virtualenv:
       pip install uwsgi
       
4. Create a file called test.py for testing and place the code in it:
     # test.py
     def application(env, start_response):
        start_response('200 OK', [('Content-Type','text/html')])
        return [b"Hello World"] # python3
        #return ["Hello World"] # python2
   
5. Now test and run the uWSGI:
      uwsgi --http :8000 --wsgi-file test.py
       
6. Now we want uWSGI to do the same thing, but to run a Django site instead of the test.py module:
 

If your project is running with pyhton manage.py runserver:8000 then,Run it with uWSGI
      uwsgi --http :8000 --module mysite.wsgi
        

Point your browser at the server; if the site appears, it means uWSGI is able to serve your Django application from your virtualenv, and this stack operates correctly
   
<-- Basic nginx installation -->
   
7. Install and start nginx:
      sudo apt-get install nginx
      sudo /etc/init.d/nginx start    # start nginx
       
Note: To restart nginx just use sudo /etc/init.d/nginx restart command.
        

And now check that the nginx is serving by visiting it in a web browser on port 80 - you should get a message from nginx:          
    “Welcome to nginx!”. 

That means these components of the full stack are working together.
   
<-- Configure nginx for your site -->
   
8. You will need the uwsgi_params file, which is available in the nginx directory of the uWSGI distribution, or from https://github.com/nginx/nginx/blob/master/conf/uwsgi_params

Copy it into your project directory. In a moment we will tell nginx to refer to it.
   
9. Now create a file called mysite_nginx.conf at
/etc/nginx/sites-available/, using the following command:

   sudo nano /etc/nginx/sites-available/mysite_nginx.conf

and paste the following code in it:
 
      # mysite_nginx.conf

      # the upstream component nginx needs to connect to
      upstream django {
       # server unix:///path/to/your/mysite/mysite.sock; # for a file 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      8000;
         # the domain name it will serve for
       server_name 127.0.0.1; # 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 /path/to/your/mysite/media;# your Django project's media files - amend as required
                }

         location /static {
             alias /path/to/your/mysite/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     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed
                }
            } 

Note: Replace project paths acoordingly.Copy and paste this file in your project directory as well.
    

10. Now symlink to this file from /etc/nginx/sites-enabled so nginx can see it.
 

sudo ln -s /etc/nginx/sites-available/mysite_nginx.conf /etc/nginx/sites-enabled/
   
11. Before running nginx, you have to collect all Django static files in the static folder. First of all you have to edit mysite/settings.py adding:
 

  STATIC_URL = '/static/'
  STATIC_ROOT = os.path.join(BASE_DIR, "static/")

  MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

  MEDIA_URL = '/media/'


and then run 'python manage.py collectstatic'.

Check the configuration syntax by typing:

  sudo service nginx configtest
Now restart the nginx 'sudo /etc/init.d/nginx restart'.
    
To check that media files are being served correctly, add an image called media.png to the /path/to/your/project/project/media directory, then visit http://example.com:8000/media/media.png - if this works, you’ll know at least that nginx is serving files correctly.

Note: If you face an error then check the nginx error log at "/var/log/nginx/error.log". If there is a permission denied error then it means your media folder doesn't have permissions for accessing. Make your media folder and its content accessible by giving it valid permissions.
   
12. Let’s get nginx to speak to the “hello world” test.py application.
           
   uwsgi --socket :8001 --wsgi-file test.py
       
   Visit: http://127.0.0.1:8000/
        

13. Using Unix sockets instead of ports:   
Edit mysite_nginx.conf, changing it to match:
            
  server unix:///path/to/your/mysite/mysite.sock; # for a file socket
  # server 127.0.0.1:8001; # for a web port socket (we'll use this first)
       
and restart nginx.

Run uWSGI again:
           
    uwsgi --socket mysite.sock --wsgi-file test.py


Try http://127.0.0.1:8000/ in the browser.If that doesn’t work.
check your nginx error log(/var/log/nginx/error.log). If you see something like:
  

connect() to unix:///path/to/your/mysite/mysite.sock failed (13: Permission denied)
        

then probably you need to manage the permissions on the socket so that nginx is allowed to use it.
       
Try uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive)
       
Now refresh the browser again.
       
If it works then you are doing good so far!
   
14. Running the Django application with uwsgi and nginx
       
Let’s run our Django application:
           
uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=666

Now uWSGI and nginx should be serving up not just a “Hello World” module, but your Django project.
       
15. Configuring uWSGI to run with a .ini file
       
Create a file called 'mysite_uwsgi.ini' at /etc/uwsgi/sites using these commands:


  sudo mkdir -p /etc/uwsgi/sites
  cd /etc/uwsgi/sites
  sudo nano mysite_uwsgi.ini

and paste the following code in it: 
      
              # mysite_uwsgi.ini file
              [uwsgi]
 

              # Django-related settings
              # the base directory (full path)
              chdir           = /path/to/your/project
              # Django's wsgi file
              module          = mysite.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    = 666
              # clear environment on exit
              vacuum          = true
           
Note: Change paths accordingly.
Also Copy this file in your project directory.We will use this to run the our project manually from the terimanl.
        

Afer placing the above code, run uswgi using this file:
           
uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file
       
Once again, test that the Django site works as expected.
   
16. Install uWSGI system-wide
So far, uWSGI is only installed in our virtualenv; we’ll need it installed system-wide for deployment purposes.

Deactivate your virtualenv by typing following command in terminal:       
 

   deactivate

and install uWSGI system-wide:
           
   sudo pip install uwsgi
       
Check again that you can still run uWSGI just like you did before:
           
   uwsgi --ini mysite_uwsgi.ini
 

17. Now create a upstart script for uWsgi:
We will create an Upstart script in the /etc/init directory, where these files are checked:

   sudo nano /etc/init/uwsgi.conf

and place the following code in it:
  description "uWSGI application server in Emperor mode"
   
  start on runlevel [2345]
  stop on runlevel [!2345]
  
  setuid user
  setgid www-data 
  exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites 

Note: Replace user with your username.

Start the uWSGI server using
  sudo service uwsgi start
Now point to the browser and check your running site.               
If it works then here's your happy moment :)

No comments:

Post a Comment