问题
I've been working on a realtime app using Node.js
and Socket.io
, and I'd like to take it from the local testing stage to testing it out with some of our users. The trouble is, if I close the ssh session to my server it also stops the server I started using node app.js
I thought about using nohup,
but I occasionally get segmentation faults or other random errors that bring down the server. I need to 1) know when (and hopefully why) my server crashed so I can both work on improving it to crash less and make sure to get it restarted. Additionally, I can't be awake 24/7 to restart the server myself, so having some sort of daemon
would be lovely.
I found forever
available via npm, but it isn't compatible with versions of Node more recent than 0.8.x
and I'm running 0.9.1
, and it doesn't seem like it gets maintained very well.
I also stumbled past distribution
and up
, but documentation and examples of building a decent app using them seem lacking.
Then there's this answer using the cluster
and os
modules. https://stackoverflow.com/a/10997753/1883464
But Node lists cluster as experimental http://nodejs.org/api/cluster.html
With the lack of answers, examples, and discussion on keeping Node servers up and running (and updating their code!) in a real production environment I'm starting to feel like I'm the first person to want to take their app to deployment ;) Somehow I'm sure there are some common answers to this problem I haven't found.
回答1:
The OS provided init system provides many advantages over any Node.js module. Hooking into the init system is the only way to ensure your app starts up automatically after a reboot.
We use Ubuntu and Upstart with a lot of success. Upstart will restart your application on crash, and can set the user-id/group before running your process. Do Not Run as Root.
Writing Upstart files is a bit of a pain, we use Node Foreman to automatically generate and export a set of upstart files from our applications Procfile
.
npm i -g foreman
cd MY_APP
nf export -o /etc/init
This will place a set of upstart files into /etc/init
that can be started and stopped with sudo start foreman
and sudo stop foreman
.
Upstart is not the only solution here, and the above can be adapted to suit other OSes as needed. On Redhat I recommend looking at systemd
. I wouldn't recomment using Mac OSX for production, but in a pinch it has launchd
.
来源:https://stackoverflow.com/questions/14776587/node-js-graceful-restarts-and-server-uptime-howto