我在 node 中有 2 个本地开发服务器。一个是基本的 nextjs 服务器,另一个是非常简单的 nodejs websocket 服务器。我想代理两者,让两者位于同一端口下。我有以下 nginx 配置:
events {
worker_connections 1024;
}
http {
server {
listen 3002;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_cache off;
}
location /ws {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_cache off;
}
location /_next/webpack-hmr {
proxy_pass http://localhost:3000/_next/webpack-hmr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_cache off;
}
}
}
问题是,如果 nextjs 服务器或 web 套接字服务器重新启动,则 nginx 将开始返回页面,502 Bad Gateway
直到我重新加载 nginx。在这种情况下,我可以做些什么来让 nginx 自动重新加载或尝试重新连接到服务器?这里还有其他更好的策略吗?
答案1
听起来 NGINX 没有与后端保持连接。
我根据 nginx 文档和他们发布的有关 websockets 的博客修改了您的配置。
https://www.nginx.com/blog/websocket-nginx/
https://nginx.org/en/docs/http/websocket.html
尝试一下,看看是否有效:
worker_processes 1;
events {
worker_connections 1024;
}
http {
sendfile off;
keepalive_timeout 65;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream node {
server 127.0.0.1:3000;
}
upstream websocket {
server 127.0.0.1:3001;
}
server {
listen 3002;
location / {
proxy_pass http://node;
proxy_set_header "Connection" "";
proxy_http_version 1.1;
}
location /ws {
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
}
}
}
如果仍然不起作用,请尝试添加proxy_set_header "Connection" "";
到 websocket 位置。