Tomcat service script

Standard

Once you have installed Tomcat from source, it becomes more convenient to create a service script to stop/start/restart the server.

Once properly configured you will be able to control tomcat like so…

service tomcat stop
service tomcat start

Begin by adding a group ‘tomcat’. This is necessary so that the tomcat server can run without root privileges.

groupadd tomcat

Create the user ‘tomcat’ and add it to the group we have created above.

useradd -s /bin/bash -g tomcat tomcat

To make Tomcat into a service create a new file called tomcat in the init.d directory. Then chmod that file to 0777 so it can be accessed by the service manager.

vi /etc/init.d/tomcat
chmod 0777 tomcat

Inside the tomcat file created above paste the following. Remember to modify the variables CATALINA_HOME and CATALINA_BASE to the location of your apache tomcat installation.

# cat /etc/init.d/tomcat
#!/bin/bash

# Tomcat7: Start/Stop Tomcat 7
#
# chkconfig: - 90 10
# description: Tomcat is a Java application Server.

# Source function library
. /etc/init.d/functions
#. /etc/sysconfig/network

CATALINA_HOME=/opt/apache-tomcat-7.0.53
CATALINA_BASE=/opt/apache-tomcat-7.0.53
TOMCAT_USER=tomcat
LOCKFILE=/var/lock/subsys/tomcat

RETVAL=0
start(){

   echo "Author: Brandon Klimek "
   echo "Starting Tomcat 7: "
   su - $TOMCAT_USER -c "$CATALINA_HOME/bin/startup.sh"
   RETVAL=$?
   echo
   [ $RETVAL -eq 0 ] && touch $LOCKFILE
   return $RETVAL
}

stop(){

   echo "Shutting down Tomcat 7: "
   $CATALINA_HOME/bin/shutdown.sh
   RETVAL=$?
   echo
   [ $RETVAL -eq 0 ] && rm -f $LOCKFILE
   return $RETVAL
}

case "$1" in
   start)
      start
      ;;
   stop)
      stop
      ;;
   restart)
      stop
      start
      ;;
   status)
      status tomcat
      ;;
   *)
      echo $"Usage: $0 {start|stop|restart|status}"
      exit 1
      ;;
esac
exit $?

If you want tomcat server to start when the server reboots. Add it to the chkconfig. This will assure that the server starts when your server is rebooted.

chkconfig tomcat on

Leave a Reply

Your email address will not be published.