系统相关
首页 > 系统相关> > Node.js Nginx – 现在怎么办?

Node.js Nginx – 现在怎么办?

作者:互联网

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

>他们应该如何一起工作?我该如何处理这些要求?
> Node.js服务器有2个概念,其中一个更好:

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

湾创建一个处理所有Node.js请求的Node.js服务器.这将读取所请求的文件并篡改其内容.因此,每个请求都会解释文件,但服务器逻辑要简单得多.

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

解决方法:

Nginx作为前端服务器工作,在这种情况下代理请求到node.js服务器.因此,您需要为节点设置nginx配置文件.

这就是我在Ubuntu框中所做的:

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

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

你应该有这样的东西:

# 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;
    }
 }

如果您希望nginx(> = 1.3.13)处理websocket请求,请在位置/部分中添加以下行:

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.com yourdomain.com

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

测试语法错误:

nginx -t

重启nginx:

sudo /etc/init.d/nginx restart

最后启动节点服务器:

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

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

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

标签:concept,nginx,node-js
来源: https://codeday.me/bug/20190911/1803146.html