Tomcat Service Script

22 July 2015

I copied this startup script from liferay. You can use this script start and stop your tomcat instance just like any CentOS standard services.

#!/bin/bash
#
# tomcat8 This shell script takes care of starting and stopping tomcat8
#
# chkconfig: 234 80 20
#
### BEGIN INIT INFO
# Provides: tomcat8
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Description: start and stop tomcat8 Tomcat instance
### END INIT INFO

TOMCAT_HOME=/usr/local/apache-tomcat-8.0.5
SHUTDOWN_WAIT=20

export JAVA_HOME=/usr/java/latest
export JAVA_OPTS="-XX:+DoEscapeAnalysis \
        -XX:+UseConcMarkSweepGC \
        -XX:+CMSClassUnloadingEnabled \
        -XX:+UseParNewGC \
        -XX:+PrintGCDetails \
        -XX:+PrintGCTimeStamps \
	      -XX:+PrintGCDateStamps \
        -XX:PermSize=64m \
        -XX:MaxPermSize=256m \
        -Xms512m \
        -Xmx512m"
export PATH=$JAVA_HOME/bin:$PATH

tomcat_pid() {
	echo `ps aux | grep $TOMCAT_HOME | grep -v grep | awk '{ print $2 }'`
}

start() {
	pid=$(tomcat_pid)
	if [ -n "$pid" ]
	then
		echo "tomcat8 is already running (pid: $pid)"
	else
		# Start tomcat
		echo "Starting tomcat8..."
		ulimit -n 100000
		umask 007
		/bin/sh $TOMCAT_HOME/bin/startup.sh
	fi

	return 0
}

stop() {
	pid=$(tomcat_pid)
	if [ -n "$pid" ]
	then
		echo "Stopping tomcat8..."
	/bin/sh $TOMCAT_HOME/bin/shutdown.sh

	let kwait=$SHUTDOWN_WAIT
	count=0;
	until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
	do
		echo -n -e "waiting for processes to exit\n";
		sleep 1
		let count=$count+1;
	done

	if [ $count -gt $kwait ]; then
		echo -n -e "killing processes which didn't stop after $SHUTDOWN_WAIT seconds\n"
		kill -9 $pid
	fi
	else
		echo "tomcat8 is not running"
	fi

	return 0
}

case $1 in
	start)
		start
	;;
	stop)
		stop
	;;
	restart)
		stop
		start
	;;
	status)
		pid=$(tomcat_pid)
		if [ -n "$pid" ]
		then
			echo "tomcat8 is running with pid: $pid"
		else
			echo "tomcat8 is not running"
		fi
	;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
	;;
esac

exit 0

Start tomcat Automatically

# chkconfig --add tomcat8
# chkconfig tomcat8 on