bitHound Blog

How to keep your node processes running forever

When starting out with bitHound I remember getting to the point where I needed to run our code on a production server. I was early in my "devops" days and quickly googled: "How to run a node process forever" where I found the awesome npm module forever.

forever is easy and quick to get running but has a few problems when running at scale. It required an interactive screen or tmux session and couldn't be configured to start when the system rebooted.

As the number of services that we ran grew and the number of provisioned servers changed we wanted a solution that was still as simple as forever. Looking outside of the normal NodeJS toolchain we found Supervisor.

Enter the Supervisor

Supervisor is a proven (circa 2004) process management tool for unix based systems that was flexible and simple to configure. It allows simple, centralized control of all services.

The configuration for a process was very easy and just required config file placed in /etc/supervisor/conf.d (the default but can be changed).

For example:

[program:serve]
environment=NODE_ENV="development"  
user=vagrant  
directory=/vagrant/serve  
command=/vagrant/serve/bin/serve  
autorestart=true  
autostart=false  

our configuration for the app process in our development environment

In this configuration example we are running our node process in development mode with the vagrant user. Since this is our development environment we have disabled autostart so we can have better control of when services are running but kept autorestart on so that we can restart the services on error. In our production configuration we have both autorestart and autostart set to true.

Like forever, you can start/stop/restart and list processes via the command line:

vagrant@dev-vm-app:/etc/supervisor$ supervisorctl status  
app:app4000                RUNNING    pid 825, uptime 1 day, 18:19:16  
app:app4001                RUNNING    pid 826, uptime 1 day, 18:19:16  
s3rver                     RUNNING    pid 1212, uptime 1 day, 22:12:53  
serf                       RUNNING    pid 1203, uptime 1 day, 22:12:53  
serve                      RUNNING    pid 18828, uptime 1 day, 1:11:05  

list the running processes

vagrant@dev-vm-app:/etc/supervisor$ supervisorctl restart app:*  
app4000: stopped  
app4001: stopped  
app4000: started  
app4001: started  

restart a named group of services

There are a lot of good management tools for working with Supervisor, from dashboards to remote control via the XML-RPC interface. A good one to check out is nodervisor which is written in node and gives you a dashboard for controlling your services and remotely viewing logs.

Supervisor is simple to get started with and helps keep our Node processes going. Check it out or reach out if you have any questions!

bitHound identifies risks and priorities in your Node.js projects.