gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:44:05 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

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

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

/etc/nginx/sites-available/创建文件yourdomain.example:

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

你应该有类似的东西:

# 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.example www.yourdomain.example;
access_log /var/log/nginx/yourdomain.example.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;
}
}

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

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

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

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

/var/www/yourdomain/app.js 创建您的 Node 服务器应用程序并在 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/');

测试语法错误:

nginx -t

重启 Nginx:

sudo /etc/init.d/nginx restart

最后启动 Node 服务器:

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

现在您应该在 yourdomain.example

中看到“Hello World”

关于启动 Node 服务器的最后一个注意事项:您应该为 Node 守护进程使用某种监控系统。有一个很棒的tutorial on node with upstart and monit .

关于Node.js + Nginx - 现在怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5009324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com