Search code examples
pythondjangoweb-servicesnginxuwsgi

Django app deployment on nGINX


I want to deploy Django application on nGINX server. I'm using uWSGI. I looked up in many tutorials but none worked. Django application runs perfectly as a standalone app. What is the simplest way to have the same app running on nGINX??

I'm stuck here and want a solution.. :-(

my www folder is in /usr/share/nginx/www

my site-enabled n conf.d and all are in /etc/nginx/

I did install uWSGI but couldn't find any folder named uwsgi which has apps-installed folder/file in it


Solution

  • Once you have created an dJango application. Just follow these steps:

    STEP 1. Create a file say uwsgi.ini in your Django Project Directory. i.e besides manage.py

    [uwsgi]
    # set the http port
    http = :<port_no>
    
    # change to django project directory
    chdir = <project directory>
    
    # add /var/www to the pythonpath, in this way we can use the project.app format
    pythonpath = /var/www
    
    # set the project settings name
    env = DJANGO_SETTINGS_MODULE=<project_name>.settings
    
    # load django
    module = django.core.handlers.wsgi:WSGIHandler()
    

    STEP 2. Under /etc/nginx/sites-available add .conf file

    server {
    listen 84;
    server_name example.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;
                      }
    
           }
    

    STEP 3. In nginx.conf, pass the request to your Django application

    Under the server { } block,

    location /yourapp {
               include uwsgi_params;
               uwsgi_pass <your app address, eg.localhost>:<portno>;
                       }
    

    STEP 4. Run the uwsgi.ini

    > uwsgi --ini uwsgi.ini
    

    Now any request to your nGINX will pass the request to your Django App via uwsgi.. Enjoy :)