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
Step 2:
Once PM2 is installed, start your application using PM2:
pm2 start app.js
Replace app.js with the entry point of your Node.js application. PM2 will start the application and manage it as a process.

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
This will output a command you’ll need to run with sudo permissions. It should look something like this:
sudo env PATH=$PATH:/usr/bin pm2 startup -u –hp
Step 4:
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
The pm2 save command saves your current PM2 process list to a file, allowing PM2 to remember and restart your applications after a reboot

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
If everything is configured correctly, your application should appear in the PM2 process list, indicating that it started on boot.

Leave a Reply