[Fixed]-Deploying Django project with Gunicorn and nginx


I’ll just summarize the steps for deploying a django application with nginx & gunicorn here:

1. Install nginx and add this to /etc/nginx/sites-enabled/default

server {

  server_name yourhost@example.com;
  access_log /var/log/nginx/domain-access.log;

  location / {
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Forwarded-For  $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_connect_timeout 10;
    proxy_read_timeout 10;

    # This line is important as it tells nginx to channel all requests to port 8000.
    # We will later run our wsgi application on this port using gunicorn.


2. Install gunicorn

$ pip install gunicorn

3. Start your django project using gunicorn and the wsgi.py file

$ cd </path/to/djangoproject_subdirectory_with_wsgi.py>

$ gunicorn wsgi -b --pid /tmp/gunicorn.pid --daemon

# --daemon parameter tells gunicorn to run in the background
# So that gunicorn continues to run even if you close your ssh session
# (You cannot remain ssh-ed into your server all the time right!)

Please do not use “wsgi.py”; you just have to use wsgi without the “.py” extension when calling gunicorn. This will start your wsgi application in the background.

4. Visit “yourhost@example.com” in your browser

Now your application must be up and running on your instance. Visit:


and see if your application is running. Do not forget to replce yourhost@example.com in the above and in the nginx configuration file before.

5. (Optional) Additional Notes

  • In Step 1, if confused; remove all existing lines from the /etc/nginx/sites-enabled/default file and put the above code inside it. (Or delete and create a new blank file and add the code)

  • If you are using virtualenv and you did apip install gunicorn inside the virtualenv in Step 2, then run the Step 3 command with respective virtualenv activated.

  • The pid of the gunicorn process is stored in /tmp/gunicorn.pid; incase you want to kill the existing gunicorn process and restart it.

  • supervisord might be used in conjunction which helps in restarting the gunicorn daemon automatically in case it dies due to some reason. This is useful in production environments.

Leave a comment