我已经在服务器上设置了Node.js和Nginx。现在我想用它,但是在我开始之前有两个问题:
How should they work together? How should I handle the requests?
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.
我不清楚如何正确使用Node.js。
你也可以用Nginx设置多个域,转发到多个node.js进程。
例如实现这些:
domain1。example ->到本地运行的Node.js进程http://127.0.0.1:4000
domain2。example ->到本地运行的Node.js进程http://127.0.0.1:5000
这些端口(4000和5000)应该用来监听应用程序代码中的应用程序请求。
/etc/nginx/sites-enabled / domain1
server {
listen 80;
listen [::]:80;
server_name domain1.example;
access_log /var/log/nginx/domain1.access.log;
location / {
proxy_pass http://127.0.0.1:4000/;
}
}
在/etc/nginx/sites-enabled / domain2
server {
listen 80;
listen [::]:80;
server_name domain2.example;
access_log /var/log/nginx/domain2.access.log;
location / {
proxy_pass http://127.0.0.1:5000/;
}
}
你也可以在一个服务器配置中为应用程序设置不同的url:
yourdomain。example/app1/* ->到本地运行的Node.js进程
http://127.0.0.1:3000
yourdomain。example/app2/* ->到Node.js进程
本地运行http://127.0.0.1:4000
在/etc/nginx/sites-enabled / yourdomain:
server {
listen 80;
listen [::]:80;
server_name yourdomain.example;
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/;
}
}
重启Nginx:
sudo service nginx restart
启动应用程序。
节点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/');
节点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/');
我们可以通过Nginx作为反向代理来轻松地设置一个Nodejs应用程序。
以下配置假设NodeJS应用程序运行在127.0.0.1:8080上,
server{
server_name domain.example sub.domain.example; # 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
}
}
在上面的设置中,你的Nodejs应用程序将
get HTTP_HOST头,在那里你可以应用域特定的逻辑来服务响应。
你的应用程序必须由一个进程管理器管理,比如pm2或supervisor来处理情况/重用套接字或资源等。
设置一个错误报告服务来获取生产错误,如哨兵或滚动条
注意:你可以设置处理域特定请求路由的逻辑,为expressjs应用程序创建一个中间件