Home >Operation and Maintenance >Linux Operation and Maintenance >How to run nodejs in the background on Linux
Using process manager PM2
PM2 is a popular process manager for running nodejs in the background in a production environment First choice. It provides many features and options, including process monitoring, automatic restart, load balancing, and more. After using PM2, we can easily run nodejs applications in the background.
Installing PM2
To use PM2, we need to install it first. Enter the following command in the terminal:
npm install -g pm2
Start the nodejs application
When starting the application, using PM2 is very simple, just enter the following command in the terminal:
pm2 start app.js
The app.js here is the entry file of our nodejs application. PM2 will automatically create a background process to run this file.
PM2 also provides many useful commands that we can use to manage the nodejs process. The following are some of the most commonly used commands:
pm2 list # 列出所有进程 pm2 stop <app-name> # 停止指定应用程序 pm2 restart <app-name># 重启指定应用程序 pm2 delete <app-name> # 删除指定应用程序
Using nohup
nohup node app.js &The app.js here is our nodejs application entry file. The "&" symbol means transferring the command to the background for execution. End runningWhen we need to stop a nodejs application running in the background, we need to first use the ps command to find the process ID of the application, and then use the kill command to end the process:
ps -ef | grep node # 找到进程 ID kill <pid> # 结束进程
sudo apt-get update sudo apt-get install screenStart screenTo start a screen terminal, we can use the following command:
screen -S <screen-name>The screen-name here is what we want The name by which the terminal is named. Running nodejs in screenNow we can run the nodejs application on the launched screen terminal. Enter the following command in the terminal:
node app.jsWhen we exit the screen terminal, the application will still be running in the background. Reconnect to the screen terminalIf you need to reconnect to the screen terminal, just use the following command:
screen -r <screen-name>The screen-name here is what we named the terminal name. End runningWhen we need to stop the nodejs application running in the background, we need to first use the Ctrl C command in the screen terminal to stop the nodejs process, and then use the following command to close the screen terminal:
exit
The above is the detailed content of How to run nodejs in the background on Linux. For more information, please follow other related articles on the PHP Chinese website!