带有 Daphne 的 Nginx 给出 502 Bad Gateway

Nginx with Daphne gives 502 Bad Gateway

我决定用 daphne 替换 uwsgi,因为我在使用 Django Channels 和 uwsgi 时遇到了问题。在遵循 this 教程之后。我在启用站点的情况下以这种方式配置了我的 nginx。我遇到的大多数其他例子都没有使用达芙妮,所以我无法理解它们。

 server {
        # the port your site will be served on
        listen      80;
        server_name .MyDomain.com;
        charset     utf-8;

        # max upload size
        client_max_body_size 75M;   # adjust to taste

        # Django media
        location /media  {
            # your Django project's media files - amend as required
            alias /home/ec2-user/MyDomainVenv/MyDomainWeb/media;
        }

        location /static {
            # your Django project's static files - amend as required
            alias /home/ec2-user/MyDomainVenv/MyDomainWeb/static;
        }


            location / {
                proxy_pass http://0.0.0.0:8001;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";

                proxy_redirect     off;
                proxy_set_header   Host $host;
                proxy_set_header   X-Real-IP $remote_addr;
                proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Host $server_name;
            }
    }

我就是这样开始达芙妮的

daphne main.asgi:channel_layer

和一个工作线程使用

python manage.py runworker

这是我的asgi.py

import os
from channels.asgi import get_channel_layer

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

channel_layer = get_channel_layer()

对可能出现的问题有什么建议吗?

我尝试访问我的网站,这就是我得到的结果

==> /var/log/nginx/error.log <==
2019/03/23 07:13:21 [error] 22191#0: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 71.231.182.18, server: MyDomain.com, request: "GET /admin/ HTTP/1.1", upstream: "http://0.0.0.0:8001/admin/", host: "www.MyDomain.com"

==> /var/log/nginx/access.log <==
71.231.182.18 - - [23/Mar/2019:07:13:21 +0000] "GET /admin/ HTTP/1.1" 502 575 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36" "-"

这是我开始使用达芙妮时得到的结果

daphne main.asgi:channel_layer
Starting server at tcp:port=8000:interface=127.0.0.1, channel layer main.asgi:channel_layer.
HTTP/2 support not enabled (install the http2 and tls Twisted extras)
Using busy-loop synchronous mode on channel layer
Listening on endpoint tcp:port=8000:interface=127.0.0.1

daphne 运行 落后于 nginx。因此,您需要将其作为上游添加到您的 nginx conf 中。

假设 daphne 在端口 8001 上 运行 并且 django 在 80

上应用
upstream channels-backend {
    server 0.0.0.0:8001;
}

并更新为

proxy_pass http://channels-backend;