【问题标题】:Docker + Node.JS + Socket.IO + Nginx (405 & Bad handshake method)Docker + Node.JS + Socket.IO + Nginx (405 & 错误的握手方法)
【发布时间】:2019-11-17 10:08:19
【问题描述】:

我有一个带有 react 前端和 nodeJS/PHP 后端的 docker 容器化应用程序(在不同的容器上工作)。我已经成功地为我的前端构建和 PHP 后端安装了带有中间容器(let'sencrypt certbot)的 https,但是与 nodejs 后端的套接字池有一些问题。当 socket.io pooling 开始时,我收到了关于 POST 请求的错误:

[发布]https://my.domain/socket.io/?EIO=3&transport=polling&t=MlE0IBv

405 不允许

当我试图通过下一次 Nginx 构建来防止这种情况时:

error_page 405 @nodejs;

我得到了与下一条消息相同的错误代码:

代码:2 消息:“握手方法错误”

我的 Nginx 配置中有一部分(nginx 是单独的 docker 容器):

upstream node {
    ip_hash;
    server node:4000; //nodejs container
}

server {
    listen 80;
    // ...redirect to https
}

server {
    listen 443 ssl;

    // .... cert's and other settings


    // front-end static react build
    location / {
        try_files $uri /index.html =404;
    }
    location /static {
        try_files $uri @nodejs;
    }

    location @nodejs {
        proxy_pass http://node;
        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;
    }

    // without this string i just got "405 Not Allowed" nginx error page
    // with this string i got probably nodejs "Bad handshake method" error
    error_page 405 @nodejs; 
}

我的 app.js 服务器代码:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const socketRouter = require('./sockets/index');
const app = express();

const server = http.Server(app);
const io = socketIO(server, {origins: '*:*'});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

io.on('connection', socketRouter.bind({}, io));

module.exports = server;

还有 index.js:

require('dotenv').config();
const app = require('./src/app');

const PORT = process.env.APP_PORT || 4000;
app.listen(PORT);

console.log('Application started on Port ' + PORT);
console.log('APP_ENV ' + process.env.APP_ENV);

【问题讨论】:

    标签: node.js nginx socket.io


    【解决方案1】:

    问题已解决。正确的配置是:

    location /static {
        try_files $uri =404;
    }
    
    location /socket.io {
            proxy_pass http://node;
            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;
            add_header  Front-End-Https   on;
    }
    
    error_page 405 @nodejs;
    

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2015-02-03
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      相关资源
      最近更新 更多