How to force a node.js application to respawn after the database connection drops

node.js

I use forever to run my Ghost blog platform atop node.js. As I understand it forever should watch for the node to drop and restart it automatically. However, if I yank the db out from under the app it doesn't recover as expected when the database becomes available again.
Logs follow:

r31c.log:Error: Connection lost: The server closed the connection.
r31c.log:error: Forever detected script exited with code: 8
r31c.log:error: Forever restarting script for 1 time
r31c.log:ERROR: connect ECONNREFUSED, sql: create table `posts` (`id` int(11) unsigned  
                not null not null auto_increment primary key, `uuid` varchar(36) not   
                null, `title` varchar(150) not null, `slug` varchar(150) not null, 
                `markdown` text, `html` text, `image` text, `featured` tinyint(1) not 
                null default '0', `page` tinyint(1) not null default '0', `status` 
                varchar(150) not null default 'draft', `language` varchar(6) not null 
                default 'en_US', `meta_title` varchar(150), `meta_description` 
                varchar(200), `author_id` int(11) not null, `created_at` datetime not 
                null, `created_by` int(11) not null, `updated_at` datetime, 
                `updated_by` int(11), `published_at` datetime, `published_by` int(11)) 
                default character set utf8,alter table `posts` add unique 
                posts_slug_unique(`slug`), bindings: 
r31c.log:error: Forever detected script was killed by signal: null
r31c.log:          throw arguments[1]; // Unhandled 'error' event
r31c.log:Error: Cannot stop process that is not running.

Best Answer

In production environments, I'd strongly suggest to try using Passenger Standalone rather than forever, to increase instances' robustness and reliability:

https://github.com/phusion/passenger/wiki/Phusion-Passenger%3A-Node.js-tutorial#wiki-deploying_standalone

If you want still use forever, you can patchy by scripting something checking if a forever instance is up, and if down, start it.

Checking the connection to the DB should be an applicative matter, though.

Related Topic