How to keep nodejs server alive using pm2


Node.js server can be run by simply pointing it to a file that we want it to run, e.g:

node file.js

Or you can also use npm to run your file if you have defined the start procedure in your package.json file.

npm start

However, as soon as you close the terminal, the server stops. Is there a way to keep the server alive? Yes there is.

How to keep nodejs server alive after closing terminal

There is a simple tool called pm2 for this purpose. It has very simple and minimal commands to manage the nodejs server processes.

To use pm2, follow these steps.

Install PM2 on server by using command:

npm install [email protected] -g

Once installed, use it to run the file instead of running it directly via node or npm. To do this, goto the same directory where you would go to launch the server using node or npm, and run this command instead:

pm2 start file.js

You can also give a custom name to the running process by using this command with –name flag like this:

pm2 start file.js --name="app name"

To start via npm start:

pm2 start npm --name "app name" -- start

To view a lit of all running processes of pm2, use command:

pm2 ls

To stop and delete a processes running through pm2, use this command (just enter the name of process in name field, not the complete js file name like file.js):

pm2 delete file

# or to delete all:
pm2 delete all

Note that if you will run the stop command like following, it will not delete the process, rather simply stop it from running state:

pm2 stop file

# or 

pm2 stop all

You can restart single or multiple apps running through pm2 like this too (also supports regular expression):

# restart single app using pm2
pm2 restart app1

# or restart multiple apps using pm2
pm2 restart app1 app2 app3

# or restart all apps matching regex pattern
pm2 restart /pattern/

You can also save and retrieve the saved pm2 process lists by using commands:

pm2 save
pm2 resurrect

Finally, to monitor pm2 and what is it doing on your server, run the command:

pm2 monit

This will show you insights about the pm2 running processes and their resource usage of your system including cpu usage, memory usage, loop delay and request per minute.

Note: pm2 can also run other programming languages including:

{
  ".sh": "bash",
  ".py": "python",
  ".rb": "ruby",
  ".coffee": "coffee",
  ".php": "php",
  ".pl": "perl",
  ".js": "node"
}

Let me know if you need help related to pm2 or nodejs server generally.


Leave a Reply

Your email address will not be published.