When node.js goes down, how can I bring it back up automatically?
Since node is basically a single process, when something goes terribly wrong, the whole application dies.
I now have a couple of apps built on express and I am us开发者_运维问答ing some manual methods to prevent extended downtimes ( process.on('uncaughtException') and a custom heartbeat monitor ).
Any suggestions from the community? Best-practices? Frameworks?
Thanks! A
Use something like forever
or use supervisor
.
Just npm link
and then sudo supervisor server.js
.
These types of libraries also support hot reloading. There are some which you use from the command line and they run node services as sub processes for you. There are others which expect you to write your code to reload itself.
Ideally what you want to move towards a full blown load balancer which is failure safe. If a single node proccess in your load balancer crashes you want it to be quietly restarted and all the connections and data rescued.
Personally I would recommend supervisor
for development (It's written by isaacs!) and a full blown load balancer (either nginx or node) for your real production server.
Of course your already running multiple node server processes in parallel because you care about scaling across multiple cores right ;)
Use forever.
"A simple CLI tool for ensuring that a given script runs continuously (i.e. forever)"
Just install it with npm
npm install forever
and type
forever start app.js
Try to look at forever module.
If you're using Ubuntu you can use upstart (which is installed by default).
$ cat /etc/init/my_app.conf
description "my_app" author "me"
start on (local-filesystems and net-device-up IFACE=eth0) stop on shutdown
respawn
exec sh -c "env NODE_ENV=production node /path/myapp/app.js >> /var/log/node.log 2>&1"
"respawn" mean that the app will be restarted if it dies.
To start the app
start my_app
For other commands
man initctl
I'll strongly recommend forever
too. I used it yesterday and its a breeze:
Install
npm install forever
Start your app
forever start myapp.js
Check if its working
forever list
Try killing your app :
ps
Get your myapp.js pid and run
kill <pid
run
forever list
and you'll see it's running again
You can try using Fugue, a library for node.js similar to Spark or Unicorn:
https://github.com/pgte/fugue
Fugue can manage any node.js server type, not just web servers, and it's set up and configured as a node.js script, not a CLI command, so normal node.js build & deployment toolchains can use it.
精彩评论