50

I have an issue with my linux server and need to reboot, before that I run my node application with pm2 start server.js without any other config. Can it auto restart my app after reboot server?

Andy Nguyen
  • 863
  • 1
  • 8
  • 20

6 Answers6

72

Not by default, but PM2 can do so using a startup script:

PM2 can generate startup scripts and configure them in order to keep your process list intact across expected or unexpected machine restarts.

After generating your startup script (read also this comment), take a look at pm2 save:

Once you started all the applications you want to manage, you have to save the list you wanna respawn at machine reboot with:

pm2 save

pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • 42
    so in short: run `pm2 startup` and when all the right processes are running that you want to automatically restart at reboot save them with `pm2 save` – Flion Nov 28 '20 at 06:59
  • 2
    @Ravindra See [`pm2-installer`](https://github.com/jessety/pm2-installer): _`pm2-installer` is designed to automate installation of pm2 as a service, particularly on Windows, even in environments without Internet access._ – pzaenger Mar 04 '21 at 10:24
  • 1
    @Flion "pm2 startup" only prints a bash command that you need to copy and execute manually. After that, the processes you saved will be restarted on boot. – Sever van Snugg Apr 13 '22 at 09:07
3

You can use this script before run pm2 save:

pm2 startup
[PM2] You have to run this command as root. Execute the following command:
      sudo su -c "env PATH=$PATH:/home/unitech/.nvm/versions/node/v14.3/bin pm2 startup <distribution> -u <user> --hp <home-path>
      

https://pm2.keymetrics.io/docs/usage/startup/

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

No, if you do not add a startup command then it will close after reboot so

you can use:

pm2 startup ubuntu

After this, it's always run after closing the server in the terminal.

Giorgi Gvimradze
  • 1,714
  • 1
  • 17
  • 34
Anil Daal
  • 1
  • 4
0

I used another alternative way on Ubuntu 20.04 and it worked!

Make sure you have saved the pm2 configuration (pm2 save)

First edit the crontab file

crontab -e

Then paste the following command

@reboot /usr/lib/node_modules/pm2/bin/pm2 resurrect && /usr/lib/node_modules/pm2/bin/pm2 start all
Pst4r8
  • 1
0

Yes, you can. Suppose your pm2 is running having some processes. First, you need to save the processes.

pm2 save

Next, you need to run the pm2 in startup. So if system rebooted your pm2 automatically started with processes.

pm2 startup

Thats it! https://pm2.keymetrics.io/docs/usage/startup/

Rajib
  • 392
  • 4
  • 16
-2

First of all I run below command

pm2 save

Then edit crontab

nano /etc/crontab

Then Add

* * * * * pm2 resurrect