Node.js + Nginx - 现在怎么办?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5009324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:52:34  来源:igfitidea点击:

Node.js + Nginx - What now?

node.jsnginxconcept

提问by Van Coding

I've set up Node.js and Nginx on my server. Now I want to use it, but, before I start there are 2 questions:

我已经在我的服务器上设置了 Node.js 和 Nginx。现在我想使用它,但是,在我开始之前有两个问题:

  1. How should they work together? How should I handle the requests?
  2. There are 2 concepts for a Node.js server, which one is better:

    a. Create a separate HTTP server for each website that needs it. Then load all JavaScript code at the start of the program, so the code is interpreted once.

    b. Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.

  1. 他们应该如何合作?我应该如何处理请求?
  2. Node.js 服务器有 2 个概念,哪个更好:

    一种。为每个需要它的网站创建一个单独的 HTTP 服务器。然后在程序开始时加载所有 JavaScript 代码,这样代码就会被解释一次。

    湾 创建一个单独的 Node.js 服务器来处理所有 Node.js 请求。这将读取请求的文件并评估它们的内容。所以每个请求都会解释文件,但服务器逻辑要简单得多。

It's not clear for me how to use Node.js correctly.

我不清楚如何正确使用 Node.js。

回答by Joao Da Silva

Nginx works as a front end server, which in this case proxies the requests to a node.js server. Therefore you need to setup an nginx config file for node.

Nginx 用作前端服务器,在这种情况下,它将请求代理到 node.js 服务器。因此,您需要为 node.js 设置一个 nginx 配置文件。

This is what I have done in my Ubuntu box:

这是我在我的 Ubuntu 盒子中所做的:

Create the file yourdomain.comat /etc/nginx/sites-available/:

yourdomain.com/etc/nginx/sites-available/以下位置创建文件:

vim /etc/nginx/sites-available/yourdomain.com

In it you should have something like:

在其中你应该有类似的东西:

# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
    server 127.0.0.1:3000;
    keepalive 8;
}

# the nginx server instance
server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com www.yourdomain.com;
    access_log /var/log/nginx/yourdomain.com.log;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://app_yourdomain/;
      proxy_redirect off;
    }
 }

If you want nginx (>= 1.3.13) to handle websocket requests as well, add the following lines in the location /section:

如果您希望 nginx (>= 1.3.13) 也处理 websocket 请求,请在该location /部分添加以下几行:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

Once you have this setup you must enable the site defined in the config file above:

完成此设置后,您必须启用上面配置文件中定义的站点:

cd /etc/nginx/sites-enabled/ 
ln -s /etc/nginx/sites-available/yourdomain.com yourdomain.com

Create your node server app at /var/www/yourdomain/app.jsand run it at localhost:3000

创建您的节点服务器应用程序并在以下位置/var/www/yourdomain/app.js运行它localhost:3000

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

Test for syntax mistakes:

测试语法错误:

nginx -t

Restart nginx:

重启nginx:

sudo /etc/init.d/nginx restart

Lastly start the node server:

最后启动节点服务器:

cd /var/www/yourdomain/ && node app.js

Now you should see "Hello World" at yourdomain.com

现在您应该在 yourdomain.com 上看到“Hello World”

One last note with regards to starting the node server: you should use some kind of monitoring system for the node daemon. There is an awesome tutorial on node with upstart and monit.

关于启动节点服务器的最后一个注意事项:您应该为节点守护程序使用某种监视系统。在 node 上有一个很棒的教程,包含 upstart 和 monit

回答by 250R

You can also setup multiple domain with nginx, forwarding to multiple node.js processes.

您还可以使用 nginx 设置多个域,转发到多个 node.js 进程。

For example to achieve these:

例如要实现这些:

These ports (4000 and 5000) should be used to listen the app requests in your app code.

这些端口(4000 和 5000)应该用于在您的应用代码中监听应用请求。

/etc/nginx/sites-enabled/domain1

/etc/nginx/sites-enabled/domain1

server {
    listen 80;
    listen [::]:80;
    server_name domain1.com;
    access_log /var/log/nginx/domain1.access.log;
    location / {
        proxy_pass    http://127.0.0.1:4000/;
    }
}

In /etc/nginx/sites-enabled/domain2

在 /etc/nginx/sites-enabled/domain2

server {
    listen 80;
    listen [::]:80;
    server_name domain2.com;
    access_log /var/log/nginx/domain2.access.log;
    location / {
        proxy_pass    http://127.0.0.1:5000/;
    }
}

回答by 0x8BADF00D

You can also have different urls for apps in one server configuration:

您还可以在一个服务器配置中为应用程序设置不同的 url:

In /etc/nginx/sites-enabled/yourdomain:

/etc/nginx/sites-enabled/yourdomain 中

server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com;

    location ^~ /app1/{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass    http://127.0.0.1:3000/;
    }

    location ^~ /app2/{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass    http://127.0.0.1:4000/;
    }
}

Restart nginx:

重启nginx:

sudo service nginx restart

Starting applications.

启动应用程序。

node app1.js

节点 app1.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from app1!\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

node app2.js

节点 app2.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from app2!\n');
}).listen(4000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:4000/');

回答by skovalyov

I proxy independent Node Express applications through Nginx.

我通过 Nginx 代理独立的 Node Express 应用程序。

Thus new applications can be easily mounted and I can also run other stuff on the same server at different locations.

因此,可以轻松安装新应用程序,我还可以在不同位置的同一服务器上运行其他内容。

Here are more details on my setup with Nginx configuration example:

以下是有关我使用 Nginx 配置示例进行设置的更多详细信息:

Deploy multiple Node applications on one web server in subfolders with Nginx

Things get tricky with Node when you need to move your application from from localhost to the internet.

There is no common approach for Node deployment.

Google can find tons of articles on this topic, but I was struggling to find the proper solution for the setup I need.

Basically, I have a web server and I want Node applications to be mounted to subfolders (i.e. http://myhost/demo/pet-project/) without introducing any configuration dependency to the application code.

At the same time I want other stuff like blog to run on the same web server.

Sounds simple huh? Apparently not.

In many examples on the web Node applications either run on port 80 or proxied by Nginx to the root.

Even though both approaches are valid for certain use cases, they do not meet my simple yet a little bit exotic criteria.

That is why I created my own Nginx configuration and here is an extract:

upstream pet_project {
  server localhost:3000;
}

server {
  listen 80;
  listen [::]:80;
  server_name frontend;

  location /demo/pet-project {
    alias /opt/demo/pet-project/public/;
    try_files $uri $uri/ @pet-project;
  }

  location @pet-project {
    rewrite /demo/pet-project(.*)  break;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://pet_project;
    proxy_redirect http://pet_project/ /demo/pet-project/;
  }
}

From this example you can notice that I mount my Pet Project Node application running on port 3000 to http://myhost/demo/pet-project.

First Nginx checks if whether the requested resource is a static file available at /opt/demo/pet-project/public/and if so it serves it as is that is highly efficient, so we do not need to have a redundant layer like Connect static middleware.

Then all other requests are overwritten and proxied to Pet Project Nodeapplication, so the Node application does not need to know where it is actually mounted and thus can be moved anywhere purely by configuration.

proxy_redirectis a must to handle Location header properly. This is extremely important if you use res.redirect()in your Node application.

You can easily replicate this setup for multiple Node applications running on different ports and add more location handlers for other purposes.

使用 Nginx 在子文件夹中的一台 Web 服务器上部署多个 Node 应用程序

当您需要将应用程序从 localhost 移动到 Internet 时,Node 会变得棘手。

Node 部署没有通用的方法。

谷歌可以找到大量关于这个主题的文章,但我一直在努力为我需要的设置找到合适的解决方案。

基本上,我有一个 Web 服务器,我希望将 Node 应用程序安装到子文件夹(即http://myhost/demo/pet-project/),而不会对应用程序代码引入任何配置依赖项。

同时我希望像博客这样的其他东西在同一个网络服务器上运行。

听起来很简单吧?显然不是。

在网络上的许多示例中,Node 应用程序要么在端口 80 上运行,要么由 Nginx 代理到根。

尽管这两种方法对某些用例都有效,但它们不符合我简单但有点奇特的标准。

这就是我创建自己的 Nginx 配置的原因,这里是一个摘录:

upstream pet_project {
  server localhost:3000;
}

server {
  listen 80;
  listen [::]:80;
  server_name frontend;

  location /demo/pet-project {
    alias /opt/demo/pet-project/public/;
    try_files $uri $uri/ @pet-project;
  }

  location @pet-project {
    rewrite /demo/pet-project(.*)  break;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://pet_project;
    proxy_redirect http://pet_project/ /demo/pet-project/;
  }
}

从这个示例中,您可以注意到我将在端口 3000 上运行的 Pet Project Node 应用程序挂载到http://myhost/demo/pet-project

首先 Nginx 检查请求的资源是否是/opt/demo/pet-project/public/ 中可用的静态文件,如果是,则按原样提供高效,因此我们不需要像 Connect 这样的冗余层静态中间件。

然后所有其他请求都被覆盖并代理到Pet Project Node应用程序,因此 Node 应用程序不需要知道它实际安装在哪里,因此可以纯粹通过配置移动到任何地方。

proxy_redirect是正确处理 Location 标头的必要条件。如果您在 Node 应用程序中使用res.redirect(),这非常重要。

您可以轻松地为在不同端口上运行的多个 Node 应用程序复制此设置,并为其他目的添加更多位置处理程序。

From: http://skovalyov.blogspot.dk/2012/07/deploy-multiple-node-applications-on.html

来自:http: //skovalyov.blogspot.dk/2012/07/deploy-multiple-node-applications-on.html

回答by aquadir

Node.js with Nginx configuration.

带有 Nginx 配置的 Node.js。

$ sudo nano /etc/nginx/sites-available/subdomain.your_domain.com

add the following configuration so that Nginx acting as a proxy redirect to port 3000 traffic from the server when we come from “subdomain.your_domain.com”

添加以下配置,以便当我们来自“subdomain.your_domain.com”时,Nginx 作为代理重定向到来自服务器的端口 3000 流量

upstream subdomain.your_domain.com {
  server 127.0.0.1:3000;
}
server {
  listen 80;
  listen [::]:80;
  server_name subdomain.your_domain.com;
  access_log /var/log/nginx/subdomain.your_domain.access.log;
  error_log /var/log/nginx/subdomain.your_domain.error.log debug;
  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://subdomain.your_domain.com;
    proxy_redirect off;
  }
}

回答by Hugo Mota

answering your question 2:

回答你的问题2:

I would use option bsimply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.

我会使用 optionb只是因为它消耗的资源少得多。使用选项'a',每个客户端都会导致服务器消耗大量内存,加载您需要的所有文件(即使我喜欢php,这是它的问题之一)。使用选项“b”,您可以加载您的库(可重用代码)并在所有客户端请求之间共享它们。

But be ware that if you have multiple cores you should tweak node.js to use all of them.

但请注意,如果您有多个核心,则应调整 node.js 以使用所有核心。

回答by svnm

I made a repository in Github which you can clone, vagrant-node-nginx-boilerplate

我在 Github 上做了一个你可以克隆的仓库,vagrant-node-nginx-boilerplate

basically the node.js app at /var/www/nodeappis

基本上 node.js 应用程序/var/www/nodeapp

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(4570, '127.0.0.1');

console.log('Node Server running at 127.0.0.1:4570/');

and the nginx config at /etc/nginx/sites-available/is

和 nginx 配置/etc/nginx/sites-available/

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

        root /var/www/nodeapp;
        index index.html index.htm;

        server_name localhost;

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

回答by Matej

You could also use node.js to generate static files into a directory served by nginx. Of course, some dynamic parts of your site could be served by node, and some by nginx (static).

您还可以使用 node.js 将静态文件生成到由 nginx 服务的目录中。当然,您站点的一些动态部分可以由节点提供服务,而另一些则由 nginx(静态)提供服务。

Having some of them served by nginx increases your performance..

其中一些由 nginx 提供服务可以提高您的性能。

回答by Renjith Thankachan

We can easily setup a Nodejs app by Nginx acting as a reverse proxy.
The following configuration assumes the NodeJS application is running on 127.0.0.1:8080,

我们可以通过 Nginx 作为反向代理轻松设置 Nodejs 应用程序。
以下配置假设 NodeJS 应用程序在 127.0.0.1:8080 上运行,

  server{
     server_name domain.com sub.domain.com; # multiple domains

     location /{ 
      proxy_pass http://127.0.0.1:8080;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }

     location /static/{
       alias /absolute/path/to/static/files; # nginx will handle js/css
     }
   } 

in above setup your Nodejs app will,

在上面的设置中,您的 Nodejs 应用程序将,

  • get HTTP_HOSTheader where you can apply domain specific logic to serve the response. '
  • Your Application must be managed by a process manager like pm2or supervisor for handling situations/reusing sockets or resources etc.

  • Setup an error reporting service for getting production errors like sentryor rollbar

  • 获取HTTP_HOST标头,您可以在其中应用特定于域的逻辑来提供响应。'
  • 您的应用程序必须由进程管理器(如pm2或主管)管理,以处理情况/重用套接字或资源等。

  • 设置错误报告服务以获取生产错误,例如哨兵滚动条

NOTE: you can setup logic for handing domain specific request routes, create a middlewarefor expressjs application

注意:您可以设置处理特定于域的请求路由的逻辑,为 expressjs 应用程序创建中间件

回答by Vkreddy Komatireddy

Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.

Nginx 可以充当反向代理服务器,就像项目经理一样工作。当它收到请求时,它会对其进行分析并将请求转发给上游(项目成员)或自行处理。Nginx 有两种根据请求的配置方式来处理请求的方法。

  • serve the request
  • forward the request to another server

    server{
     server_name mydomain.com sub.mydomain.com;
    
     location /{ 
      proxy_pass http://127.0.0.1:8000;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }
    
     location /static/{
       alias /my/static/files/path;
     }
    

    }

  • 为请求服务
  • 将请求转发到另一台服务器

    server{
     server_name mydomain.com sub.mydomain.com;
    
     location /{ 
      proxy_pass http://127.0.0.1:8000;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }
    
     location /static/{
       alias /my/static/files/path;
     }
    

    }

Server the request

服务器请求

With this configuration, when the request url is mydomain.com/static/myjs.jsit returns the myjs.jsfile in /my/static/files/pathfolder. When you configure nginx to serve static files, it handles the request itself.

使用此配置,当请求 url 为时, mydomain.com/static/myjs.js它返回myjs.js文件/my/static/files/path夹中的 文件。当您配置 nginx 以提供静态文件时,它会自行处理请求。

forward the request to another server

将请求转发到另一台服务器

When the request url is mydomain.com/dothisnginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.

当请求 url 为 mydomain.com/dothisnginx 时,会将请求转发到 http://127.0.0.1:8000。运行在 localhost 8000 端口的服务将接收请求并将响应返回给 nginx,而 nginx 将响应返回给客户端。

When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.

当您在端口 8000 上运行 node.js 服务器时,nginx 会将请求转发到 node.js。编写 node.js 逻辑并处理请求。就是这样,您的 nodejs 服务器在 nginx 服务器后面运行。

If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.

如果你想运行 nodejs 以外的任何其他服务,只需在不同的端口上运行另一个服务,如 Django、flask、php,并在 nginx 中配置它。