To install PM2 and ensure it automatically restarts your Node.js application, follow these steps:
Step 1: Install Node.js and npm
If you don’t already have Node.js and npm installed, you can install them using the following commands:
sudo apt update
sudo apt install nodejs npm -y
Step 2: Install PM2
Install PM2 globally using npm:
sudo npm install -g pm2
Step 3: Start your application with PM2
Navigate to your application directory and start your application with PM2:
pm2 start app.js
Replace app.js
with the entry point of your application.
Step 4: Save the PM2 process list and corresponding environments
To ensure your PM2 processes are resurrected on reboot, save the current process list:
pm2 save
Step 5: Configure PM2 to start on boot
PM2 provides a built-in method to generate and configure the startup script for different platforms. Run the following command to configure PM2 to start on boot:
pm2 startup
This command will output a line of code that you need to run with sudo privileges. It will look something like this:
sudo env PATH=$PATH:/usr/bin pm2 startup <your-init-system> -u <your-username> --hp <your-home-path>
For example, on a system using systemd
, it might look like:
sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u user --hp /home/user
Run the command that is generated by pm2 startup
.
Step 6: Verify that PM2 is set up correctly
To verify that PM2 is correctly set up to start on boot, you can reboot your system:
sudo reboot
After the system reboots, check the status of your PM2 processes:
pm2 status
You should see your application running.
Additional Tips
- Monitor your application: PM2 provides monitoring tools. You can monitor logs and other details using:
pm2 monit
- Logs: Access logs using:
pm2 logs
By following these steps, you’ll have PM2 installed and configured to automatically restart your Node.js application on system reboot.