Running hapijs as deamon

How can I run hapijs as a server deamon on a Linux box? Right now, I'm running it as a user process for development with the node index.js command for the main page, but in the long run it should be www-data or whatever else user that runs the process.

If you want to run node as a daemon without any extra tools, you can use nohup:

nohup node index.js &

However, the following tools can do this and also have some other really useful features such as automatic restart on exit, log redirection and in the case of PM2, clustering:

PM2: https://github.com/Unitech/pm2

Forever: https://github.com/foreverjs/forever

If you want your service to start when your machine start/reboots, you can use something like Upstart (on ubuntu) or System-V:

https://www.digitalocean.com/community/tutorials/how-to-write-a-linux-daemon-with-node-js-on-a-vps

To run as different user to the user you're logged in with:

sudo -u somebody node index.js

Please note that none of the above is specific to hapi but rather applies to any Node.js app.

I use supervisord and it works great.

In short you have to configure supervisord to start your hapijs application. In addition you need to configure nginx or apache to reverse proxy requests to your hapijs application.

You can find detailed instructions on set up at http://blog.risingstack.com/operating-node-in-production/

PM2 is the best option hands down. It scales from local development through to production without issue.

First Step:

npm install -g pm2

The -g flag is simply for installing to globally so it's available as system command.

Second Step:

pm2 start index.js

The start command simply replaces node index.js Behind the scenes it runs the node process but as a daemon.

PM2 Actual Use Case

cd projects/my-app
npm install -g pm2
npm install
NODE_ENV=development pm2 start index.js -n my-app

pm2 stop my-app
pm2 restart my-app
pm2 status
pm2 logs my-app
pm2 m

Those should be enough to get you going. The nice thing about PM2 is it works great in a CI/CD environment as well since you can recall process by name. Finally out of the box it does log rotation and a few other awesome things to keep you going even if stuff goes south. Apps will also auto restart if they crash (obv. configurable).

Additional configuration allows PM2 to watch files on disk and restart the app as they change. This is great for development as you can code + save files and the API you're building in HapiJS will simply restart and your changes are live.