Django、Gunicorn 和 Nginx 的 Bad Gateway 502 错误

Bad Gateway 502 Error with Django, Gunicorn and Nginx

我正在尝试 运行 使用 Gunicorn 和 Nginx 在 Django 上进行项目。在 DigitalOcean OneClick 安装图像上,我的项目在没有 virtualenv 和全局 Django 安装的情况下工作正常。但是当我为不同的 Django 版本创建虚拟环境时,我无法让它工作。好心人请为我提供一些使用虚拟环境在 Ubuntu 上托管多站点的帮助。以下是我的 Gunicorn 虚拟环境设置:

description "Gunicorn daemon for Django project"

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]

# If the process quits unexpectadly trigger a respawn
respawn

setuid django
setgid django
chdir /home/django

exec gunicorn \
    --name=myproject2\
    --pythonpath=myproject2\
    --bind=127.0.0.1:9500 \
    --config /etc/gunicorn.d/gunicorn.py \
    myproject2.wsgi:application

我的第二个项目的 Nginx 设置是:

upstream ashyanaa_server {
    server 127.0.0.1:9500 fail_timeout=0;

}


server {
    listen 80;
    listen [::]:80;


    root /home/django/myproject2;
    index index.html index.htm;

    client_max_body_size 4G;
    server_name www.myproject2.com;


    keepalive_timeout 5;

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf)$ {
        expires 365d;

    }



    # Your Django project's media files - amend as required
    location /media  {
        alias /home/django/myproject2/media/;
    }

    # your Django project's static files - amend as required
    location static/static-only {
        alias /home/django/myproject2/static-only/; 

    }
    # Django static images
    location /static/myproject2/images {
        alias /home/django/myproject2/static-only/images/;
    }


    # Proxy the static assests for the Django Admin panel
    location /static/admin {
       alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin;
    }

    location / {


        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://myproject2_server;


    }

我的第一个项目设置与第二个项目唯一不同的是我在第二个项目中使用虚拟环境,显然我必须为新项目使用不同的端口。

'Bad Gateway' 表示 Nginx 在连接 Gunicorn 进程时遇到问题。

  1. 仔细检查启动 Gunicorn 的服务(由您发布的 upstart 脚本定义的服务)实际上是 运行
  2. 当您执行 curl http://127.0.0.1:9500/ 时会发生什么?你收到 Gunicorn 的回复了吗?

这是对Nginx不了解造成的。我在 Nginx 中添加了 www.mydomain.com 但我有在浏览器中输入不带 www 的域名的习惯。我只是添加了 "mydomain.com" 和 "www.mydomain.com"。所以现在两者都可以正常工作。如果您的所有设置都正确并且仍然得到 502,则其他人可以遵循,这意味着您要查找的地址未在 Nginx 中列出。这可能是原因之一。感谢大家的帮助。