How to start nodejs application automatically on openwrt - Arduino Yun - - linux

I am trying to have a nodejs application start automatically on system boot. Basically all I need is to run the command node /dir/app.
I am using openwrt on an Arduino Yun. And have tried a couple things.
On the openwrt website it said I can do this. https://wiki.openwrt.org/inbox/procd-init-scripts :
#!/bin/sh /etc/rc.common
USE_PROCD=1
start_service() {
procd_open_instance
procd_set_param command node ///www/www-blink.js
procd_close_instance
}
I have also tried changing the dir to /www/www-blink.js not ///
However i'm not sure what i'm doing wrong as nothing comes up when I try run it with /etc/init.d/node-app start I am obviously writing the code wrong but i'm not sure what it should exactly look like.
The other thing I have tried is the node modules forever and forever-service.
I downloaded them on my computer using npm install -g forever and forever-service aswell. I transfered them to usr/lib/node_modules on my arduino yun. However when I try to use and forever(-service) commands it says
-ash: forever: not found
I have tried a couple other things, however nothing has worked. Any help would be greatly appreciated.
-- I also need to be able to start my express script with npm start not node app but I guess the first thing is getting it to work at all.

you can put the starting command (node /dir/app &)in the /etc/rc.local script. This will start your nodejs application automatically on system boot.

OpenWRT procd has a "respawn" parameter, which will restart a service that exits or crashes.
# respawn automatically if something died, be careful if you have an
# alternative process supervisor if process dies sooner than respawn_threshold,
# it is considered crashed and after 5 retries the service is stopped
procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
So, you cold just add:
procd_set_param respawn 60 5 5
or something like that to your OpenWRT procd initscript. This 60 5 5 means it will wait 5s between respawns (middle parameter), and if it respanws more than 5 times (last parameter) in 60s (first parameter), it will disable the service ("restart loop" detected).
Refer to this page for more information:
https://openwrt.org/docs/guide-developer/procd-init-scripts

You need to execute your node application like a Linux Service.
Upstart is perfect for this task
Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running.
If you have an app like this (for example):
// app.js
var express = require('express')
var app = express()
var port = process.env.PORT
app.get('/', function(req, res) {
res.send('Hello world!')
})
app.listen(port)
With a package.json like this:
{
"name": "my-awesome-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.13.3"
},
"scripts": {
"start": "node app.js"
}
}
We create a upstart configuration file called myAwesomeApp.conf with the following code:
start on runlevel [2345]
stop on runlevel [!2345]
respawn
respawn limit 10 5
setuid ubuntu
chdir /opt/myAwesomeApp.conf
env PORT=3000
exec npm start
To finish, put your application (app.js and package.json) in the /opt/myAwesomeApp.conf and copy the configuration file myAwesomeApp.conf in /etc/init/
This is all, now you just need to run service myAwesomeApp start to run your node application as a service

I've never used procd before, but it likely needs the full path to node (e.g., /usr/bin/node). You'd need to make the line something like procd_set_param command /usr/bin/node /www/www-blink.js, assuming the file you want to run is /www/www-blink.js. You can locate node by running which node or type -a node.

Related

starting, stopping and restarting windows services using node js

Can someone explain how I can start or stop a windows service using a node program? Not a NodeJS service running on Windows, but specifically a Windows service itself, and that too, using NODEJS. There are lots of articles as to how to kill or start a NodeJS service, but not of what I am in need of here. There is an article though on StackOverflow in the following link:
Node js start and stop windows services
But I am either not doing it right because I have not understood it the way it should be or it doesn't do what I need it to do. Please help me out. Don't know why, but there are just almost no articles online about this.
USE os-services module
npm install os-service
It is loaded using the require() function:
var service = require ("os-service");
A program can then be added, removed and run as a service:
service.add ("my-service");
service.remove ("my-service");
service.run (function () {
// Stop request received (i.e. a kill signal on Linux or from the
// Service Control Manager on Windows), so let's stop!
service.stop ();
});
Use bat file to stop and start node server or user nodemon package.
And use windows task scheduler
#echo off
cd "D:\sam\Projects\NodeSchedule // path of node project i.e. index.js
taskkill /IM node.exe -F
start /min cmd /C "node index.js"
goto :EOF

Running forever script from Google Cloud Platform App Engine startup script

I have edited the startup-script variable for one of my instances running on the Google Cloud Platform App Engine. I'd like it to call a forever script to make sure my node app is running. So I added:
cd /opt/bitnami/apps/myapp
forever start --workingDir /opt/bitnami/apps/myapp/ --sourceDir /opt
/bitnami/apps/myapp/ app.js
after the #!/bin/bash line (also tried without the cd as it's not really necessary based on my command). But once the vm is started, running a forever list doesn't list my forever task as having ever started. If I copy and paste that forever command into a gcloud terminal and run, the task shows up fine and my app starts no problem.
Am I not calling this correctly somehow within the bash script?
The simple answer is that GAE does this by default. No need for forever or PM2. There are certain health checks that GAE does on the Docker container holding your app, and if they do not pass the instance is automatically restarted
If you want granular control over these checks (called Legacy Health Checks) you can add this to your app.yaml file:
health_check:
enable_health_check: True
check_interval_sec: 5
timeout_sec: 4
unhealthy_threshold: 2
healthy_threshold: 2
There is also updated mechanisms (called Updated Health Checks) that are still in beta, but can be used instead
The proper way to start your nodejs app on appengine is to specify the "scripts" field in your package.json, as the documentation
Below is an example borrowed from this sample
"scripts": {
"start": "node ./bin/www",
"test": "cd ..; npm run t -- appengine/analytics/test/*.test.js"
},
If you however, are only interested in running a node script, and not interested in the features that come with Google app engine, then you may simply run it on a Google Compute Engine instance.

How can I run grunt as a daemon?

I am running a packaged nodejs webserver that allows for reading of epub files (Readium-JS), and it is started with the grunt command.
However, if I run this on my VPS the server dies as soon as my terminal connection ends.
How can I run this task as a daemon?
I have looked at options like grunt-forever and grunt-daemon but the way the Gruntfile is written using load-grunt-config is messing with my mind and I can't piece together how to isolate the server code.
Here's the solution I found:
As was suggested above, using pm2
However, when I ran
pm2 start grunt
I got an error saying that the grunt module did not exist, which was weird.
So I ended up writing a script which worked:
-- start.js --
var pm2 = require('pm2');
pm2.connect(function() {
pm2.start({
script : '/usr/local/bin/grunt', // Script to be run
args: '--force',
}, function(err, apps) {
pm2.disconnect();
});
});
After running node start.js from the command line, everything sailed smoothly.

Start server node.js with forever on ubuntu

I been searching alot and no result with same problem as me.
I have a Node.js application and I want to start it with forever start app.js, the process starts but no website found when i try in browser. The process is in the list when I write forever list.
Npm start works fine but I cant use nodejs/node app.js or my_file.js.. It gives no error or something just new command line with no output in terminal.
So anyone know why I cant start the app with nodejs app.js or forever start app.js .. No files works.
Thanks!
In express 4 you should write :
forever ./bin/www
And if you check your package.json file you can see :
"scripts": {
"start": "node ./bin/www"
}
It's the npm start script
Alternatively, you can try using PM2.
It does a great job at keeping your app alive, and has some really useful features such as load balancing, no downtime, and a web interface to monitor your processes.
In addition, I find it dead simple to use.

Forever.js starting and restarting multiple scripts

My web app has 3 main node.js components: website, feeds and jobs.
To start these I am using forever:
//forever.js
var forever = require('forever');
function start(name){
forever.start( ['coffee', name + '.coffee'], { /* log options */ } )
};
start('website');
start('feeds');
start('jobs');
What I first noticed is that if I run script it wont run it as a daemon. ( Which is most likely normal )
node forever.js
So what I did next was run the forever.js script with forever. I am not sure if this is correct, there is also a forever.startDaemon so not sure which one I should use.
forever start forever.js
This works but the problem is that I would like to restart all the processes when a new version of my app is published. I am using git's post-receive hook to run the forever.js the first time but if I do this on each post-recieve it will just spawn 3 processes each time.
So I guess I need a way to restart 3 processes if they are already running. I thought to do this with forever.list but the documentation only say:
forever.list (format, callback)
Returns a list of metadata objects about each process that is being run using
forever. This method is synchronous and will return the list of metadata as such.
Only processes which have invoked forever.startServer() will be available from
forever.list()
First of all I am not sure what format means and second it expects a callback but then it says its synchronous. Which is a little confusing and I am not sure how to use list.
In the end all I want to do is start/restart 3 node.js processes on git's post-receive hook.
I think the best way to do this is:
forever start website.js
forever start feeds.js
forever start jobs.js
and then in your git post-receive hook:
forever restart website.js
forever restart feeds.js
forever restart jobs.js
Wrapping these node processes inside a single process is not a good idea. I now personally use Supervisord with monit instead of forever (supervisord is more stable & powerful than forever IMHO).
I do it like this:
#!/bin/sh
# Make sure we're in the right place
DIR=$(cd $(dirname "$0"); pwd)
cd $DIR
echo "[ I am $USER and I changed PWD to $DIR ]"
forever restart --spinSleepTime=2000 api_daemon.js || (forever start --spinSleepTime=2000 api_daemon.js && forever list)
Works like a charm, I never get duplicate processes using ./run.sh
To read logs, I use
tail -f /path/to/.log
Yes, it's possible. You need to use npm run forever command to run a script.
Add this to your package.json
"scripts": {
"forever" : "forever start api/api-server.js && forever start www/www-server.js && forever start upload/upload-server.js && forever start static/static-server.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
You can create package.json using npm init

Resources