Node.js + Nginx - What now?

后端 未结 12 1770
抹茶落季
抹茶落季 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:42

    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/');
    

提交回复
热议问题