【问题标题】:How to Configure uwsgi + nginx + Django + websocket?如何配置 uwsgi + nginx + Django + websocket?
【发布时间】:2020-01-23 13:33:42
【问题描述】:

我成功部署了 uwsgi + nginx + Django。但我想使用 websocket 与我的服务器通信。

我按照本教程处理正常的 https 请求。 https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html

nginx conf文件设置如下:

upstream django {
    server unix:///path/to/your/mysite/mysite.sock; # for a file socket
}

# configuration of the server
server {
    # the port your site will be served on
    listen 443 ssl; # managed by Certbot
    # the domain name it will serve for
    server_name example.com; # substitute your machine's IP address or FQDN
    charset     utf-8;



    location /static {
        alias /path/to/your/mysite/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed
    }
}

我搜索了很多,发现人们建议添加这些设置:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect off;

它不起作用。我没有使用proxy_pass,因为我已经在使用uwsgi_pass django;,并且我的客户端尝试使用websocket连接到我uwsgi_pass到django的相同url(位置)。我查看了 uwsgi 文档并找到了这个页面: https://uwsgi-docs.readthedocs.io/en/latest/WebSockets.html

根据这个页面,如果我只添加 --http-websockets 选项,我不需要额外的设置。所以我做了。像这样:

/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --http-websockets www-data --daemonize /var/log/uwsgi-emperor.log

在 /etc/rc.local 中添加。该命令也不起作用。我还尝试将http-websockets = true 添加到 .ini 文件中。它甚至使 uwsgi 停止。所以我删除了那个选项。

这里有什么问题?

对于每个 websocket 请求,我都会收到 400 Bad Request。我看到的唯一数据是(操作码 -1)。没有graphql错误信息。

【问题讨论】:

  • 我知道使用nginx > gunicorn > django 堆栈肯定会起作用,如果其他一切都失败了,试试吧:)
  • @DusanGligoric 好的。我会尝试gunicorn。但我没有看到关于使用 websocket 的好文档。我找到的唯一一个是:flask-socketio.readthedocs.io/en/latest/#gunicorn-web-server
  • 我也是,我知道使用nginx > gunicorn > django :D。 @Beginner,您可以按照 gunicorn 文档来实现它,这里是如何使用套接字设置它的指南。 docs.gunicorn.org/en/latest/deploy.html#systemd
  • 您在哪里看到 400 错误请求?您是否在 django 中记录错误以便查看 django 日志?你检查过你的 uwsgi 日志吗?
  • @dirkgroten 我通过网络选项卡在 Chrome 开发人员模式下看到 400 错误。屏幕没有显示任何内容,因为它是一个 graphql 请求。我确实在 django 中记录错误,但此错误未显示在 django 级别。我将 django 日志发送到 uwsgi,它只显示“错误请求:/graphql/”

标签: django nginx websocket uwsgi graphql-subscriptions


【解决方案1】:

您需要将套接字类型从 .sock 更改为 net (ip:port)。 并在 NGinx“代理”和带有 django 的服务器上使用此构造。

【讨论】:

    猜你喜欢
    • 2014-05-29
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2015-02-19
    • 2019-03-15
    • 2014-05-31
    相关资源
    最近更新 更多