How to Use pm2 startup for Application Auto-Start on Server Boot
Introduction:
The pm2 startup command is essential for managing Node.js applications in a production environment. PM2 is a popular process manager for Node.js that keeps applications running by automatically restarting them if they crash. It also provides useful features like logging, load balancing, and monitoring. The pm2 startup command configures PM2 to start automatically when the server boots, ensuring your applications are always running. Follow these steps to set up your application for automatic startup
Prerequisite:
1. Server root credentials.
Step 1:
Before using the PM2 startup command, ensure that PM2 is installed globally on your server. If you haven’t installed PM2 yet, you can do so with:
npm install pm2@latest -g |
Once PM2 is installed, start your application using PM2:
pm2 start app.js |
Step 3:
To ensure your application automatically starts on system boot, use the pm2 startup command. This command generates and configures a startup script based on your operating system.
pm2 startup |
sudo env PATH=$PATH:/usr/bin pm2 startup -u –hp |
Run the output command as instructed by PM2. For example:
sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u your_user –hp /home/your_user |
Step 5:
After setting up the startup command, save the current process list so PM2 knows which applications to restart on boot:
pm2 save |
Step 6:
To confirm that your application will start on boot, you can reboot your server and check if the application starts automatically:
sudo reboot |
Step 7:
After the reboot, connect back to your server and check the PM2 process list:
pm2 list |