【问题标题】:Binding a Node.js Application on a Port with Nginx使用 Nginx 在端口上绑定 Node.js 应用程序
【发布时间】:2018-01-12 03:57:12
【问题描述】:

我正在尝试在 Nginx Ubuntu 17.04 上使用 SSL 的端口上设置用于生产的 Node.js 应用程序。到目前为止,我已经启动并运行了 SSL Nginx 服务器。

这是我的 Nginx 配置文件的样子:

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

root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;

server_name example.com www.example.com;

location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

location ~ /\.ht {
    deny all;
}
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

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

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

}

这就是我的 Node.js 应用程序的样子:

#content of index.js    
'use strict';

const http = require('http');
http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/html; charset=utf-8',
  });
  res.write('<h1>I’m a Node app!</h1>');
  res.end(3000, 'localhost')
}).listen();
console.log('http://example.com:3000/');

我想知道如何使用现有的 Nginx 配置将这个 Node.js 应用程序绑定到带有 SSL 的端口上。

【问题讨论】:

  • 您必须将 NodeJS 应用程序绑定到不同的端口,然后让 Nginx 将请求代理到它。 PS:搜索nginx reverse proxy nodejs,你会发现很多设置示例。
  • @razvanz 谢谢!这实际上是我的问题:) 好吧!会的。
  • @razvanz 最终它正在收听location /app2 {},但它显示错误 502 Bad Gateway

标签: javascript node.js ssl nginx nginx-reverse-proxy


【解决方案1】:

您必须使用 nginx 作为 nodejs 应用程序的反向代理。

例如,让节点在 3000 端口上运行,然后在你的 nginx 配置文件中执行类似的操作。

如果节点应用程序是服务器中唯一的东西,

server {
   listen 443;
   <-- snip -->

   location / {
      proxy_pass http://localhost:3000;
   }

   <-- snip -->
}

如果您在服务器上运行其他类似 php 应用程序的东西,请创建另一个服务器块并为您的应用程序提供单独的 server_name。

server {
   listen 443;
   server_name nodeapp.mysite.com;
   <-- snip -->

   location / {
      proxy_pass http://localhost:3000;
   }

   <-- snip -->
}

【讨论】:

  • 感谢您的回答 :) 我需要反向代理和 Web 服务器。我已经发布了我的答案。
【解决方案2】:

这是我对问题的回答。 有两个错误:

1) 编辑添加server闭包文件:

location ~ ^/(nodeApp|socket\.io) {
   proxy_pass http://localhost:3000;
}

SocketIO 默认使用 /socket.io 路径,所以需要配置 Nginx 使其不仅代理 /nodeApp 请求,还代理 /socket.io

2) 在 Node.js 服务器文件中再进行一次编辑。替换:

http.createServer((req, res) => {` to `app.get('/node', function(req, res) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多