我应该如何配置nginx以在TCP服务器之前作为反向代理Websocket服务器运行?

时间:2018-11-21 14:39:45

标签: node.js nginx

我有一个运行在127.0.0.1:1905上的tcp服务器

我已经像这样配置了nginx

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

    upstream websocket {
        server http://127.0.0.1:1906;
    }

    server {
        listen 8020;
        location / {
            proxy_pass http://127.0.0.1:1905;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }
    }
}

我尝试使用以下方法打开套接字:

npm install -g wscat
wscat --connect ws://127.0.0.1:1906

我知道

error: connect ECONNREFUSED 127.0.0.1:1906

我在这里做错了什么?我是同时使用nginx和Web套接字的新产品,所以我不完全了解发生了什么,也不知道问题可能在哪里。

1 个答案:

答案 0 :(得分:0)

上游配置看起来有问题,您可以尝试以下吗?

upstream websocket {
   server http://127.0.0.1:1906;
}
server {
    listen 8020;
    location / {
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
    location /webserver {
        proxy_pass http://127.0.0.1:1905;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
   }
}

如果还需要配置其他服务器,则可以为 / webserver 配置其他上游或上述其他位置。因此 / 将是您的套接字服务器,而 / webserver 将是另一台服务器(普通的http服务器)

相关问题