Running Java applications as daemon on Linux
Recently I found the need to create an init.d script for a java app and since I had a hard time finding an example, I came up with this
vim /usr/local/bin/myAPP-stop.sh
#!/bin/bash
# Grabs and kill a process from the pidlist that has the word myAPP.jar
pid=`ps aux | grep start.jar | grep -v grep | awk ‘{print $2}’`
kill -9 $pid
vim /usr/local/bin/myAPP-start.sh
#!/bin/bash
JAVA=”/usr/bin/java”
myAPP_DIR=”/usr/local/myAPP_DIR/”
LOG_FILE=”/var/log/myAPP.log”
cd $myAPP_DIR
nohup $JAVA -jar myAPP.jar 2> $LOG_FILE &
vim /etc/init.d/myAPP
#!/bin/bash
# myapp daemon
# description: myAPP
case $1 in
start)
echo -n “Starting myAPP”
/bin/bash /usr/local/bin/myAPP-start.sh
echo “.”
;;
stop)
echo -n “Stopping myAPP”
/bin/bash /usr/local/bin/myAPP-stop.sh
echo “.”
;;
restart)
echo -n “Restarting myAPP”
/bin/bash /usr/local/bin/myAPP-stop.sh
/bin/bash /usr/local/bin/myAPP-start.sh
echo “.”
;;
*)
echo “usage: myAPP {start|stop|restart}”
exit 1
;;
esac
exit 0
chmod +x /usr/local/bin/myAPP-start.sh /usr/local/bin/myAPP-stop.sh /etc/init.d/myAPP
update-rc.d myAPP defaults
This script work perfectly under Ubuntu 12.04, but it should apply to other distributions with little changes as well.

