Search code examples
javascriptnode.jshttpservercron

How to keep node js server active?


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

Solution

  • 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