用Gunicorn和nginx部署Django项目

2024-04-26 18:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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得到这个布局。 有人能帮我吗? 谢谢你


Tags: 项目djangopyhttpvirtualenvinit指南nginx
1条回答
网友
1楼 · 发布于 2024-04-26 18:22:12

我将在这里总结使用nginx&gunicorn部署django应用程序的步骤:

一。安装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

三。使用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应用程序。

四。在浏览器中访问“yourhost@example.com”

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

http://yourhost@example.com/

看看你的应用程序是否在运行。不要忘记在前面的上面和nginx配置文件中回复yourhost@example.com

5个。(可选)附加注释

  • 在步骤1中,如果有疑问,请从/etc/nginx/sites-enabled/default文件中删除所有现有行,并将上面的代码放入其中。(或删除并创建新的空白文件并添加代码)

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

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

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

相关问题 更多 >