Nginx

使用 nginx 代理 sockets.io 的多個實例

  • July 18, 2015

我在 nginx 後面執行了兩個單獨的 node.js 應用程序。這兩個應用程序都使用 socket.io 和 express。一個在埠 5000 上提供服務,另一個在埠 5001 上提供服務。但是我們需要它們都通過埠 80 訪問,這樣當客戶端訪問<http://example.com/app1>時,它們會被轉發到第一個應用程序,並且http:// example.com/app2第二個應用程序。

當我們只有一個應用程序時,我們在 nginx Sites Enabled 配置文件中進行了此設置:

  location /app1/ {
           proxy_pass http://127.0.0.1:5000/;
   }


   location /socket.io {
           proxy_pass http://127.0.0.1:5000/socket.io/;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection "upgrade";
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header Host $host;
           proxy_http_version 1.1;
   }

那工作得很好。但是,現在我們正在添加第二個應用程序,我不確定如何設置轉發。顯然,socket.io 不能再轉發到 5000,因為來自 app2 的連接需要連接超過 5001。

當然,必須有一種方法可以將 socket.io 轉髮指定為每個應用程序的子域,但我不知道那會是什麼。

您能給我的任何建議將不勝感激。

我遇到了確切的問題,我發現了這個簡單的解決方法:

從您的 js/html 文件配置您的客戶端 socket.io 以從子目錄連接(預設的 socket.io 設置將使您的 socket.io 連接路由到http://example.com/socket.io 。你可以在這裡找到如何做到這一點:讓 socket.io 從子目錄執行

所以你會想要在你的客戶端文件上:

var socket = io.connect('http://example.com', {path: "/app1socket"});

和其他應用程序:

var socket = io.connect('http://example.com', {path: "/app2socket"});

然後,像以前一樣,為 nginx 中的每個應用程序套接字創建路由:

location /app1socket/ {
   proxy_pass http://127.0.0.1:3000/socket.io/;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_set_header Host $host;
   proxy_cache_bypass $http_upgrade;
}

location /app2socket/ {
   proxy_pass http://127.0.0.1:4000/socket.io/;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_set_header Host $host;
   proxy_cache_bypass $http_upgrade;
}

假設您的應用程序在 nginx 下執行的原因是將 http 請求代理到本地執行的應用程序,請按照標准設置保留伺服器文件配置。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(4000, '127.0.0.1');

您現在可以在 nginx 下製作多個 socket.io 應用程序。

引用自:https://serverfault.com/questions/645643