Deploying Django project with Gunicorn and nginx

余生长醉 提交于 2019-12-02 16:32:06

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 127.0.0.1 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.
    proxy_pass http://127.0.0.1:8000/;
  }

}

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 127.0.0.1:8000 --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:

http://yourhost@example.com/

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.

Referring this link may help. It contains a step-by-step process:

http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/

Please use this link for simple tutorial. which helps you to deploy easily and you can find how to map with domain also. LINK HERE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!