NGINX在同一端口配置Node.js Express和TCP服务器?

时间:2017-09-25 15:50:31

标签: node.js express nginx tcp server

我正在尝试设置我的节点服务器,使用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上连接到我的服务器。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要为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