Keep Express.js server always Running after the terminal close
In this tutorial, you are going to learn how to keep your Express.JS server always running even after closing the terminal.
If you are a beginner to Node.JS and start learning Express.JS then you may wonder thinking that it doesn’t make sense to stop the Node-based website when shutting down the terminal.
In other words, there is no means to use the Express web server if it is not possible to keep it running forever.
Well, hopefully, there are some ways to overcome this and keep your Express.js based website always accessible even after you close the terminal. But in this tutorial, I will let you know how to do it using the PM2 module.
Using PM2 process manager to keep running Node.js app always in the background
PM2 is a production-ready Node module that is able to stay running your Node-based application in the background until you close it using the same PM2. Even I also love this process manager and use it for my Express-based web applications and websites.
To start using PM2, you have to be in the directory in the terminal where your Node project is located. After that install it like any other Node module from npm:
npm i pm2
It will complete the installation of the PM2 within a moment. After that everything is ready. There is no need to write any JavaScript code, not even a single line.
Now suppose, your main JavaScript file for your Express app is index.js. Then below is the command to start the server using PM2:
pm2 start index.js
That’s it… Now you can close the terminal and you can check the server is always running. Go and open the Express website and you can now access it always. It is now running forever in the background.
You can notice that you don’t have to write command like node index
or node index.js
. This is because, PM2 module is now being used to run the app as well as keep it running in the background all the time.
Advantages of using PM2
If you are using PM2 for your Node.js app, then there are a number of advantages you will get which are given below:
- PM2 is able to handle all the logics for you internally so that you don’t have to change anything in your code.
- PM2 can update your app without any downtime by using
pm2 reload <app name>
command. - PM2 has the feature of scaling up your Node.js app in real time with the help of its clustering feature.
- It can automatically prevent from any server downtime. It is done by restarting the app automatically when a crash occur.
Leave a Reply