Node.js: How to create "smooth" restart of launched app?
Is it 开发者_高级运维possible to create smooth restart of node.js application without downtime at all?
Thanks ;)
I took an approach similar to PartlyCloudy, but just using multiple node threads on the same process, and using the OS as the load balancer instead of a separate one.
So I have code in my "app.coffee" code that's stolen from:
- https://github.com/isaacs/node-supervisor/issues/40
- http://nodejs.org/api/cluster.html
I only added a "setTimeout". For a period of 5-20 seconds I may have 16 forks on my 8 cores instead of 8, but that's better for me than downtime.
var childProcesses, cluster, i, numCPUs, signals, _i;
cluster = require('cluster');
numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
childProcesses = [];
for (i in numCPUs) {
childProcesses[i] = cluster.fork();
}
signals = ["SIGINT", "SIGTERM", "SIGQUIT"];
for (i in signals) {
process.on(signals[i], function() {
// THIS IS WHAT KEEPS IT UP
setTimeout(function() {
var j;
for (j in childProcesses) {
childProcesses[j].kill();
}
process.exit();
}, 20000);
});
}
cluster.on('exit', function(worker, code, signal) {
childProcesses.push(cluster.fork());
});
} else {
app.listen(3000);
}
Depending on your use case, application style and statefulness, you might also start multiple node processes running the same application and put a reverse proxy/load balancer in front (i.e. HAProxy). In case of a crash of a process, the load balancer will dispatch new requests to other processes, as long as the node has not yet restarted. This also improves performance by utilizing multiple cores. However, shared states such as sessions might be more tricky to handle (i.e. externally using Redis).
in case of an crash of your script you will everytime have a downtime, it's not possible to prevent. But you can use forever.js to automagically restart your script whenever it crashes.
精彩评论