Cute Dog

Setting up pm2 for Auto-Restart on Reboot and File Changes

Feb 2, 2025

To set up pm2 so that your application auto-restarts both on reboot and when it detects file changes, follow these steps:

1. Install pm2

If you don’t have pm2 installed, you can install it globally on your server by running the following command:

npm install pm2 -g

2. Start Your Application with pm2

To start your application with pm2, navigate to your project directory and run:

pm2 start app.js  # Replace with your actual entry point file

This command will start your app and pm2 will begin managing it.

3. Enable pm2 to Auto Restart on Reboot

To ensure that pm2 restarts your application when the server is rebooted, you need to set up pm2 as a startup service. Run the following command:

pm2 startup

This will generate a command that looks something like this:

sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u ubuntu --hp /home/ubuntu

Run the generated command with sudo privileges to set up the startup configuration.

4. Save the Current pm2 Process List

After starting your application, save the process list so that pm2 will know what processes to restore when the server reboots. Run:

pm2 save

This will save the current list of applications that pm2 is managing.

5. Monitor File Changes with pm2

To make sure pm2 watches your project directory for file changes, enabling watch mode is required. You can start pm2 in watch mode like this:

pm2 start app.js --watch  # Replace with your actual entry point file

This will restart your app automatically whenever a file changes in your project directory.

6. Add Custom File Watch Directories (Optional)

By default, pm2 watches the entire project directory for file changes. However, you can configure pm2 to watch specific directories or exclude others using the --ignore-watch option. Here’s an example:

pm2 start app.js --watch --ignore-watch="node_modules"

This configuration will watch for file changes, but it will ignore any changes in the node_modules directory.

7. Set up pm2 Log Rotation (Optional)

As your application runs, pm2 will generate log files. To ensure these logs don’t fill up your disk space, set up log rotation. You can use pm2’s built-in log rotation feature:

pm2 install pm2-logrotate

This will install the log rotation module and keep your logs from growing uncontrollably.

8. Verify pm2 Configuration

To check that everything is set up correctly, run:

pm2 list  # To see the status of your running apps
pm2 logs  # To view logs

Now pm2 is configured to:

  • Auto-restart your app if the server reboots.
  • Auto-restart the app when files in the project directory change.

This should help you keep your app running smoothly without manual intervention.

mounish
M

Mounish Vatti's Assistant

Ask me anything