与Gunicorn和nginx一起部署Django项目

时间:2013-11-23 14:00:43

标签: python django nginx gunicorn ubuntu-server

我是django的新手,我想知道如何用nginx和gunicorn建立我的django项目。我阅读了本指南:http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ 但它对我的项目不起作用。 我认为这是由于我的项目的特定结构,即:

├──icecream
│   ├── settings
│   |    ├── __init.py
│   |    ├── base.py
│   |    ├── local.py
│   |    ├── production.py
│   ├── __init__.py
│   ├── urls.py
│   ├── wsgi.py
├── manage.py

我从https://github.com/twoscoops/django-twoscoops-project得到了这个布局。 有人可以帮帮我吗? 谢谢

3 个答案:

答案 0 :(得分:34)

我将总结使用nginx& amp;部署django应用程序的步骤。枪声:

1。安装nginx并将其添加到/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。安装gunicorn

$ pip install gunicorn

3。使用gunicorn和wsgi.py文件

启动您的django项目
$ 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!)

请不要使用“wsgi.py”;你只需要在调用gunicorn时使用没有“.py”扩展名的wsgi。这将在后台启动您的wsgi应用程序。

4。访问浏览器中的“yourhost@example.com”

现在您的应用程序必须在您的实例上启动并运行。访问:

http://yourhost@example.com/

并查看您的应用程序是否正在运行。不要忘记在上面和之前的nginx配置文件中重复使用 yourhost@example.com

5。 (可选)附加说明

  • 在第1步中,如果感到困惑;从/etc/nginx/sites-enabled/default文件中删除所有现有行,并将上面的代码放入其中。 (或者删除并创建一个新的空白文件并添加代码)

  • 如果您正在使用virtualenv并且您在步骤2中的virtualenv中执行了pip install gunicorn,则运行步骤3命令并激活相应的virtualenv。

  • gunicorn进程的pid存储在/tmp/gunicorn.pid中;如果您想要杀死现有的gunicorn进程并重新启动它。

  • supervisord可以结合使用,这有助于在因某种原因导致死亡时自动重启gunicorn守护进程。这在生产环境中很有用。

答案 1 :(得分:2)

参考此链接可能有所帮助。它包含一个循序渐进的过程:

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

答案 2 :(得分:0)

请使用此链接获取简单教程。这有助于您轻松部署,您也可以找到如何使用域映射。 LINK HERE