如何保持 Node.js 服务器活动?

huangapple go评论66阅读模式
英文:

How to keep node js server active?

问题

这是您提供的代码和问题的翻译:

我的问题听起来很熟悉,但稍微有些调整。问题是:我有一个监听HTTP请求的Node.js服务器,一旦建立连接,它会向客户端发送一些响应。在我继续之前,让我展示我的代码:

这个服务器部署在Namecheap.com托管的cPanel上。

服务器监听连接,当连接建立时,我开始以60秒的间隔向客户端发送数据,数据显示如下:

1 2023年5月17日 02:27:51 GMT-0400(东部夏令时)
2 2023年5月17日 02:28:51 GMT-0400(东部夏令时)
2 2023年5月17日 02:29:51 GMT-0400(东部夏令时)
4 2023年5月17日 02:30:51 GMT-0400(东部夏令时)
4 2023年5月17日 02:31:51 GMT-0400(东部夏令时)

在连接上,我有一个1秒的间隔,直到客户端断开连接,将数据发送到Firebase。

我的挑战是:我希望连接持续更长时间,至少12小时或更长时间,然后断开连接。我使用浏览器进行测试,并惊讶地发现每次都在大约5分钟后断开连接。我尝试更改server.keepAliveTimeout等设置,但没有帮助。我还尝试了Cron Jobs,但仍然在约5分钟后断开连接。问题显然出现在我的服务器上。

如果需要更多解释,请告诉我。我是Node.js的学生,这是我的第一个服务器,我依赖于您的帮助。

英文:

My question sounds familiar I am sure, however a bit adjusted. The problem is: I have a node js server which listens for http requests, once a connection is made it posts some responses to the client. Before I say more let me bring in my code:

const https = require('https');
const http = require('http');
http.globalAgent.keepAlive = true; //for persistant connections (last long connections)
const express = require("express");
const app = express();

const server = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    
    setInterval(() => {
        
        server.getConnections(function(error, count) {

            res.write(count + '   ' + new Date() + "\n");
        
        });
        
    }, 60000);
        
}, app).listen();

server.on("connection", function(sokk) {
    
    sokk.keepAliveTimeout = 86400000 + 1000;
    sokk.headersTimeout = 86400000 + 2000;
    
    setInterval(() => {
        
        rootRef.child("Servers/Server").child("conn").set(Date.now());
        
    }, 1000);
    
    sokk.on("data", data => {
        console.log(data);
    });
    
    console.log("A new connection was made by a client.");
    
});

// server.setTimeout(86400000); // A value of 0 will disable the timeout behavior on incoming connections: https://nodejs.org/dist/latest-v6.x/docs/api/all.html#http_request_settimeout_timeout_callback

// This is the important stuff
server.keepAliveTimeout = 86400000 + 1000;
se

rver.headersTimeout = 86400000 + 2000;

This server is deployed on cpanel on namecheap.com hosting.

The server listens to connections, and when a connection is made um posting data with number of connections and current date, also I am posting current timestamp to firebase so that I know when the last time the client was connected and disconnected.

Allow me to layout how my server is working:

  1. When a connection is made, I start posting data to the client on an interval of 60 seconds, and the data appears as follows:

> 1 Wed May 17 2023 02:27:51 GMT-0400 (Eastern Daylight Time)
> 2 Wed May 17 2023 02:28:51 GMT-0400 (Eastern Daylight Time)
> 2 Wed May 17 2023 02:29:51 GMT-0400 (Eastern Daylight Time)
> 4 Wed May 17 2023 02:30:51 GMT-0400 (Eastern Daylight Time)
> 4 Wed May 17 2023 02:31:51 GMT-0400 (Eastern Daylight Time)

  1. Inside on connection, I have an **interval **of 1 second to post data to firebase until the client is disconnected.

MY CHALLENGE
My challenge is: I want the connections to last longer like for 12 hours or more before disconnected. I am using my browser to check this and to my surprise there is a disconnection after something like 5 minutes every time. So I tried to change things like server.keepAliveTimeout to a high time like 2days, it did not help, I reduced it to 0, it did not help, I deleted it hoping the default will help, it did not help. I tried also: server.headersTimeout which is higher than server.keepAliveTimeout and it did not help. I went on to add these two sokk.keepAliveTimeout and sokk.headersTimeout inside a connection for specific connection it did not help.

I also tried: server.setTimeout(86400000); it still disconnects after 5 minutes or so, I tried to set it to 0 as server.setTimeout(0); and still no changes. Then I tried the same inside a connection it does not help.

Finally I thought maybe my PC or browser does not have a constant connection so I went on to try **Cron Jobs **in cpanel as follows:

curl https://server.mydomain.com/ 

and I set the Cron Jobs to record on my *email *and look an example of the emails um getting:

> 1 Wed May 17 2023 02:35:17 GMT-0400 (Eastern Daylight Time)
> 1 Wed May 17 2023 02:35:22 GMT-0400 (Eastern Daylight Time)
> 1 Wed May 17 2023 02:35:27 GMT-0400 (Eastern Daylight Time)
> 1 Wed May 17 2023 02:35:32 GMT-0400 (Eastern Daylight Time)
> 1 Wed May 17 2023 02:35:37 GMT-0400 (Eastern Daylight Time)

This tells me that the Cron Jobs are doing their job but still they get disconnected after about 5 minutes, 6 on maximum. So clearly the problem is on my server.

The reason why I need this server is to keep some intervals running, like posting current time to firebase, however the intervals stop when the connections are closed, and the intervals only start again when there is a new connection.

HINTS
I can have multiple connections at the same time, but they get closed at the same time regardless of how long each has been in connection. The first connection may run for about 5 minutes or 6, and when I create another connection it might get terminated the same time when the first one is closed. The issue in not about having multiple connections, but about keeping a connection last longer, even for at least one hour. or a day if possible because my tasks work only if there is a connection.

According to my consultation I was told that my server sleeps if there is no **traffic **to it, so when it sleeps the interval tasks sleeps too. This brought the idea of Cron Jobs, so I am sending a cron job once in five minutes. So I have traffic now but connections are being either terminated or timeout for the reason I do not know. My wish was to have a cron job once in a day which stays connected the whole day so that my interval tasks keep going all day.

FORGIVE ME
If there is any part which is not clearly explained please ask me and I clarify, I am a node js student and this is my first server, so I am relying on your help good people!

Just to add on to what I have said above. I tried:

  1. server.keepAliveTimeout = 86400000 + 1000;
  2. server.headersTimeout = 86400000 + 2000;
  3. Cron Jobs
  4. sokk.setTimeout(0);
  5. sokk.setTimeout(86400000);
    6 I tried to use a business hosting

答案1

得分: 1

pm2 npm模块是启动node服务器的最佳方式,但当机器重新启动时,需要再次使用pm2模块开始node服务。但是,如果使用systemctl服务启动服务,无需在重新启动机器后启动node服务。

  • 在/lib/systemd/system路径上创建node服务文件 sudo nano /lib/systemd/system/node.service
  • 根据您的配置放入以下代码

> [Unit]
> Description=env.js
> Documentation=https://example.com
> After=network.target
>
> [Service]
> Environment=NODE_PORT=3001
> Type=simple
> User=ubuntu
> ExecStart=/usr/bin/node /home/ubuntu/server.js
> Restart=on-failure
>
> [Install]
> WantedBy=multi-user.target

  • 运行守护进程重新加载命令 sudo systemctl daemon-reload
  • 启动node服务命令 sudo systemctl start node.service
  • 检查Node服务状态命令 sudo systemctl status node.service
  • 如果要停止node服务命令 $ sudo systemctl stop node.service
  • 如果要重新启动node服务命令 $ sudo systemctl restart node.service
  • Node服务器日志命令 journalctl -f

参考 - https://nodesource.com/blog/running-your-node-js-app-with-systemd-part-1/,https://www.cloudbees.com/blog/running-node-js-linux-systemd

英文:

The pm2 npm module is the best way to start the node server but when a machine is rebooted, you need to begin node service again using the pm2 module. But when you start service using systemctl service no need to start node service after rebooting the machine.

  • Make node service file on /lib/systemd/system path sudo nano /lib/systemd/system/node.service
  • Put this below code according to your configuration

> [Unit]
> Description=env.js
> Documentation=https://example.com
> After=network.target
>
> [Service]
> Environment=NODE_PORT=3001
> Type=simple
> User=ubuntu
> ExecStart=/usr/bin/node /home/ubuntu/server.js
> Restart=on-failure
>
> [Install]
> WantedBy=multi-user.target

  • Run demon reload command sudo systemctl daemon-reload
  • Start node service command sudo systemctl start node.service
  • Node service status check command sudo systemctl status node.service
  • If you want stop node service command $ sudo systemctl stop node.service
  • If you restart node service command $ sudo systemctl restart node.service
  • Node server logs command journalctl -f

Ref - https://nodesource.com/blog/running-your-node-js-app-with-systemd-part-1/,https://www.cloudbees.com/blog/running-node-js-linux-systemd

答案2

得分: 0

Cpanel 中,以与安装模块相同的方式打开终端并安装 pm2

npm install pm2 -g

安装成功后,不要再使用"设置 Node.js 应用程序"中的启动按钮来启动应用程序,而是使用终端按如下方式启动应用程序:

pm2 start app.js

app.js 是启动文件,请用您自己的文件名替换。

一旦您以这种方式启动应用程序,它将一直运行直到您关闭它,只要没有任何错误。要检查应用程序已经运行了多长时间,请使用以下终端命令:

pm2 list
英文:

In Cpanel, open your terminal the same way you installed the modules and install pm2

npm install pm2 -g

Then after a successful installation, instead of starting the app using start button in Setup node js app you need to use terminal to start the app as follows:

pm2 start app.js

ie. app.js is the start up file, replace with yours.

Once you start your app like this it will run live up until you close it, as long there is no any errors.
To check how long your app has been live use the following terminal:

pm2 list

huangapple
  • 本文由 发表于 2023年5月17日 15:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定