简体   繁体   中英

How NodeJS server running for ever

I use Putty. When I start server with "node X.js", putty start server running. If I exit from putty the server stop. How I can keep it running and make it default running after restart or reboot the server (computer)?

I have centos 5.10. Thank you!

I use pm2 to do it

To install pm2

sudo npm install -g pm2

To generate startup script

pm2 startup ubuntu(centos in your case)

Then pm2 will prompt the command for you to run, in my case, it is like

PM2 You have to run this command as root
PM2 Execute the following command :
PM2 sudo env PATH=$PATH:/usr/bin pm2 startup ubuntu -u USERNAME

Then you could run

sudo env PATH=$PATH:/usr/bin pm2 startup ubuntu -u USERNAME

Then you could see

PM2 Generating system init script in /etc/init.d/pm2-init.sh
PM2 Making script booting at startup...
PM2 -ubuntu- Using the command su -c "chmod +x /etc/init.d/pm2-init.sh && update-rc.d pm2-init.sh defaults"
Adding system startup for /etc/init.d/pm2-init.sh ...
   /etc/rc0.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
   /etc/rc1.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
   /etc/rc6.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
   /etc/rc2.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
   /etc/rc3.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
   /etc/rc4.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
   /etc/rc5.d/S20pm2-init.sh -> ../init.d/pm2-init.sh

PM2 Done.

Once you have started the apps and want to keep them on server reboot do:

 pm2 save

You can refer to Startup script section in https://github.com/Unitech/pm2#startup-script

There are several ways, I personally like forever.

sudo npm install -g forever
forever start app.js &

note that ending with & will fork the process to background.

You can later check the process with

forever list

To run it when your system restarts you can add to cron

@reboot forever start app.js  &> /dev/null

Remember to point to the absolute location of app.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM