Environment: debian/ubuntu
This script can monitor cpu/memory usage of your node application, and start/stop it via a web interface or command line
Step 1. install startup and monit (they are normally preinstalled in ubuntu)
sudo apt-get install upstart monit
then edit /etc/defaults/monit, set startup=1
Step 2. in /etc/init/, create a config of your application, ex: your_app.conf with code
#!upstart description "your_app" author "Hongbo LU" start on (local-filesystems and net-device-up IFACE=eth0) stop on runlevel 0 respawn # restart when job dies respawn limit 5 60 # give up restart after 5 respawns in 60 seconds script exec start-stop-daemon --start --make-pidfile --pidfile /var/run/your_app.pid --chdir /path/to/your/app --chuid user:usergroup --exec NODE_ENV=production /usr/local/bin/node index.js >> /var/log/nodejs/node.log 2>&1 end script
NOTICE:
- user:usergroup must be the one who owns Node
- modify the log folder as you wish
- in order to use relative paths in Node, we must change directory to project’s folder
Step 3. edit file /etc/monit/monitrc, enable web interface
include /etc/monit/conf.d/* set daemon 120 # Poll at 2-minute intervals set logfile syslog facility log_daemon set alert youremail@email.com set httpd port 2812 and use address localhost allow localhost # Allow localhost to connect allow admin:Monit # Allow Basic Auth
Step 4. create file /etc/monit/conf.d/your_app.monitrc
check process plusnode
with pidfile "/var/run/your_app.pid"
start program = "/sbin/start your_app"
stop program = "/sbin/stop your_app"
if 2 restarts within 3 cycles then timeout
if totalmem > 100 Mb then alert
if children > 255 for 5 cycles then stop
if cpu usage > 95% for 3 cycles then restart
if failed port 80 protocol http
request /valid_url/
with timeout 5 seconds
and if failed port 443 type tcpssl protocol http
request /valid_url/
with timeout 5 seconds
then restart
NOTICE:
- modify your_app as you wish
- modify server port as you wish
- monit will try to reach localhost:8080/valid_url to check the server status, so make sure your valid_url is valid
Step 5. now you can control your app. via web interface: localhost:2812 or via command:
#upstart command sudo start your_app sudo status your_app sudo stop your_app #the commands above are shortcuts of initctl: initctl start your_app initctl status your_app #to check if the upstart conf is valid initctl check-config #to reload upstart configs initctl reload-configuration #monit command sudo monit sudo monit start your_app
NOTICE:
- if your app. stopped, monit will restart it automatically.
