Skip to content

Instantly share code, notes, and snippets.

@ocombe
Last active January 29, 2020 10:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ocombe/3826e5800011843e75a3 to your computer and use it in GitHub Desktop.
Save ocombe/3826e5800011843e75a3 to your computer and use it in GitHub Desktop.
Daemon for permanent node web server on linux.
#!/bin/bash
#
### BEGIN INIT INFO
# Provides: http-server
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable http-server of /var/www.
### END INIT INFO
# Source function library.
. /lib/lsb/init-functions
pidFile=/var/run/http-server.pid
logFile=/var/log/forever/output.log
nodeApp=/usr/lib/startServer.js
start() {
echo "Starting $nodeApp"
# This is found in the library referenced at the top of the script
start_daemon
# Notice that we change the PATH because on reboot
# the PATH does not include the path to node.
# Launching forever with a full path
# does not work unless we set the PATH.
PATH=/usr/local/bin:$PATH
export NODE_ENV=production
#PORT=80
forever start --pidFile $pidFile -l $logFile -d $nodeApp
RETVAL=$?
}
restart() {
echo -n "Restarting $nodeApp"
forever restart $nodeApp
RETVAL=$?
}
stop() {
echo -n "Shutting down $nodeApp"
forever stop $nodeApp
RETVAL=$?
}
status() {
echo -n "Status $nodeApp"
forever list
RETVAL=$?
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
restart
;;
*)
echo "Usage: {start|stop|status|restart}"
exit 1
;;
esac
exit $RETVAL

Install dependencies:

sudo npm i -g forever http-server

Add server script

Copy startServer.js to /usr/lib/startServer.js

Create service

  • Copy content of http-server in /etc/init.d/http-server

  • Make the service executable & add it to boot

sudo chmod +x /etc/init.d/http-server
sudo update-rc.d http-server defaults 80 
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("sudo http-server /var/www -p 80", puts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment