Node.js + Nginx - What now?

后端 未结 12 1616
抹茶落季
抹茶落季 2020-11-22 00:26

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:

  1. How should they work together? How should I handl
相关标签:
12条回答
  • 2020-11-22 00:39

    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,

      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,

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

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

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

    0 讨论(0)
  • 2020-11-22 00:40

    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).

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

    0 讨论(0)
  • You can also have different urls for apps in one server configuration:

    • yourdomain.com/app1/* -> to Node.js process running locally http://127.0.0.1:3000
    • yourdomain.com/app2/* -> to Node.js process running locally http://127.0.0.1:4000

    In /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:

    sudo service nginx restart
    

    Starting applications.

    node 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

    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/');
    
    0 讨论(0)
  • 2020-11-22 00:45

    Node.js with Nginx configuration.

    $ 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”

    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;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 00:49

    I proxy independent Node Express applications through Nginx.

    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:

    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(.*) $1 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 Node application, so the Node application does not need to know where it is actually mounted and thus can be moved anywhere purely by configuration.

    proxy_redirect is 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.

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

    0 讨论(0)
  • 2020-11-22 00:50

    answering your question 2:

    I would use option b simply 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.

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

    0 讨论(0)
提交回复
热议问题