Quick Way To Run A Nodejs App As A Service Using Forever Service
Summary:
We explore running a Nodejs app forever as a service(in background and after reboots). Note that this has been tested only Ubuntu 14.04 LTS only and might not work as expected on other OSs.
Short Steps:
1. npm install -g forever
2. npm install -g forever-service
3. forever-service install nameofservice --script yournodejsapp.js
4. sudo service start nameofservice
A Sample Nodejs app
For our example we are going to create a simple http web server using the example at the official express library github https://github.com/expressjs/serve-static
1 2 3 4 5 6 7 | var express = require('express') var serveStatic = require('serve-static') var app = express() app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']})) app.listen(3000) |
Let's say we save the file as server.js. You can then test it by running
node server.js
If you want to test if it's running then you can open another console and type
nc -v localhost 3000
Forever
Now let's say you close the console, your app will stop to run which is normal. There are lot of ways to run an executable in background but the easiest way for a Nodejs developer is Forever. You can install it easily with
npm install -g forever
Using Forever is pretty easy, you can run your app using
forever start server.js
Then you can check running apps using
forever list
Then you can stop running apps using their index
forever stop 0
More information can be found here https://github.com/foreverjs/forever
However forever is only going to run your app in background and it will not automatically restart your app when your server is rebooted.
Forever-Service
Forever service addresses this specifically. There are other ways of running your app on startup but again I think this is going to be easier for Nodejs developers. Installation is pretty simple(make sure you installed forever first)
npm install -g forever-service
Install your app as a service
forever-service install nameofservice --script server.js
Then you can start the service like any other service
sudo service start nameofservice
if you are not sure that the script is running you can still netcat
nc -v localhost 3000
More information can be found at: https://github.com/zapty/forever-service
Final Words
As always we hope that this post was helpful. Don't hesitate to comment if you have any question!
Comments
Post a Comment