Running your server forever using forever in Node.js

Akash Gutha
InstructorAkash Gutha

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 5 years ago

Previously to tackle manual restarts due to server crashes , process management tools were used.

Forever is one such module that is runs on the node ecosystem. So, we need not move away from the rich ecosystem of Node.js.

Use npm install --global forever to install forever module globally.

[00:00] First, we'll start by installing Forever as a global module. Forever allows us to run scripts continuously whether it is written in Node.js or not. We will leverage this functionality to run our server continuously, and restart if any failure might occur.

[00:14] Let's clear this out. Let's import the native HTTP module as HTTP. We will use this module to create our base server. Now, we'll create a server using the createrServer function exposed by the HTTP module.

[00:31] The createServer takes in a function which is called for each incoming server request. The function takes in two parameters. The first one is the incoming request, and the second one is the response that we will populate with data and send back to client. Let's leave the function empty for now.

[00:48] Let's get a reference to the server object, and we will name it server. Now, we can start listening on the server using the listen function and passing in a port number. I'll be using 8080. Feel free to use any open port.

[01:03] Now, we'll start building a response to send back to the client. Let's write "Welcome to Egghead server" into the response stream. Then we'll end the response using the end function. This allows us to send the response back to the client.

[01:19] Now, we'll start a server on Node and ping the server from our browser. If we navigate to our localhost 8080, we should get "Welcome to Egghead server." Now, we'll simulate a crash on our server, and then use Forever to fix this crashing issue.

[01:35] We'll check for the incoming URL and break a server if it is /break. The crash can be simulated using process.exit, which kills the whole process, essentially bringing our server to a halt. Let's stop running the server and restart it.

[01:56] If we navigate to the /break URL, we should break the server. As you can see, the Node process is also executed. Now, we'll start a server using Forever. We can go and check our server, whether it's running. As you can see, it's running.

[02:14] Now, if we try to access the break path, we will break the server. We'll check if our server has restarted. Yes, it has restarted. If we break it again, as you can see, you can see that it has logged a script restarted in one and a script restarted at two.

[02:35] Whenever you break the server, it's going to restart it again, making sure that your server's downtime will be as minimal as possible.