【问题标题】:NGINX config with Node.js Express and TCP server on same port?NGINX 配置与 Node.js Express 和 TCP 服务器在同一端口上?
【发布时间】:2018-03-06 15:57:54
【问题描述】:

我正在尝试设置我的节点服务器,它使用 express 在端口 3000 上提供文件,并使用 net 库在端口 5052 上为 TCP 服务器提供服务,所以:

const express = require('express');
const app = express();
const httpServer = require('http').Server(app);
const io = require('socket.io').listen(httpServer);
const path = require('path');
const net = require('net');

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, './public/index.html'))
});

let server = net.createServer(function(socket) {
 // Left out for brevity
}

server.listen(5052, 'localhost');

httpServer.listen(3000, () => {
  console.log('Ready on port 3000');
});

在本地,这一切都很好。我可以加载 localhost:3000 并获得我的 HTML 服务,它可以很好地连接到 socket.io。我也可以完美连接5052端口的服务器,生活还不错。我只是无法让 nginx 正确地为它服务。这是我所拥有的:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name mycoolproject.com www.mycoolproject.com;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }

  listen 443 ssl;
  ssl_certificate /etc/letsencrypt/live/mycoolproject.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/mycoolproject.com/privkey.pem;
  include /etc/letsencrypt/options-ssl-nginx.conf;

  ssl_dhparam /etc/ssl/certs/dhparam.pem;

  if ($scheme != "https") {
      return 301 https://$host$request_uri;
  }

}

server {
    listen 5053;

    server_name mycoolproject.com www.mycoolproject.com;

    location /{
        proxy_pass http://localhost:5052;
                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;
    }
}

当我导航到mycoolproject.com 时,我的网站加载正常,所以快递方面工作正常。我只是无法连接到我在 5053 上的服务器。有什么想法吗?

【问题讨论】:

  • 一个问题,在你说它工作的地方,你也用 nginx 服务吗?

标签: node.js express nginx tcp server


【解决方案1】:

你需要为 Nginx 配置一个不同的端口,5052 正被 Node.js 占用。

server {
    listen 5053;

    server_name mycoolproject.com www.mycoolproject.com;

    location /{
        proxy_pass http://localhost:5052;
                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;
    }
}

然后你就可以连接到 mycoolproject.com:5053

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多