与Gunicorn和nginx一起部署Django项目

Bet*_*use 12 python django nginx ubuntu-server gunicorn

我是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
Run Code Online (Sandbox Code Playgroud)

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

Pra*_*tal 34

我将在这里总结一下使用nginx和gunicorn部署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/;
  }

}
Run Code Online (Sandbox Code Playgroud)

2.安装gunicorn

$ pip install gunicorn
Run Code Online (Sandbox Code Playgroud)

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!)
Run Code Online (Sandbox Code Playgroud)

请不要使用"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并且您pip install gunicorn在步骤2中执行了virtualenv,则运行步骤3命令并激活相应的virtualenv.

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

  • supervisord可能会一起使用,这有助于自动重启gunicorn守护进程,以防它因某种原因而死亡.这在生产环境中很有用.