Simple init script for Tomcat

With an init script for your Tomcat (or other programs) you can handle two demands:

  1. You can specify the required options like JAVA_OTPS in this script
  2. Your Tomcat will be startet after server restart

In this post I will use a Tomcat for Solr as example. So first we need to define a init script:

$ touch /etc/init.d/solr
$ chmod a+x /etc/init.d/solr

The content of /etc/inid.d/solr looks like this:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          tomcat-solr
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Solr
# Description:       Solr Tomcat
### END INIT INFO

NAME="solr"
TOMCAT_DIR="/opt/tomcat-solr"
export JAVA_OPTS="-Dsolr.solr.home=/my-solr-home-dir"
export CATALINA_PID="$TOMCAT_DIR/catalina.pid"

case "$1" in
    start)
        $TOMCAT_DIR/bin/startup.sh
        ;;
    stop)
        $TOMCAT_DIR/bin/shutdown.sh -force
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    status)
        if [ -f $CATALINA_PID ] && ps --no-heading -p `cat $CATALINA_PID`; then
                echo "$NAME is running"
        else
                echo "$NAME is not running"
        fi
        ;;
    *)
        echo "Usage: /etc/init.d/$NAME {start|stop|restart|status}" >&2
        exit 1
        ;;

esac

exit 0

Now we can test the script with service solr status

Last step is to create the required symlinks for the several runlevels. This can be done with update-rc.d:

$ update-rc.d solr defaults 99
 Adding system startup for /etc/init.d/solr ...
   /etc/rc0.d/K99solr -> ../init.d/solr
   /etc/rc1.d/K99solr -> ../init.d/solr
   /etc/rc6.d/K99solr -> ../init.d/solr
   /etc/rc2.d/S99solr -> ../init.d/solr
   /etc/rc3.d/S99solr -> ../init.d/solr
   /etc/rc4.d/S99solr -> ../init.d/solr
   /etc/rc5.d/S99solr -> ../init.d/solr

Used Versions: Ubuntu 12, Tomcat 7
References:

Advertisements
Posted in Tomcat. Tags: . Leave a Comment »

Tomcat: Getting the process ID

If you want to get the process id (PID) of your tomcat you can do something like this:

ps h -C java -o "%p:%a" | grep catalina | cut -d: -f1

If you want to kill this tomcat, because it didn’t shut down properly you can use the following:

kill -9 `ps h -C java -o "%p:%a" | grep catalina | cut -d: -f1`

A better way is to set the environment variable CATALINA_PID. If this variable is set the PID is written in the specified file (here catalina.pid) on tomcat startup.

export CATALINA_PID=/opt/tomcat/catalina.pid
/opt/tomcat/bin/startup.sh

Now killing the tomcat is also easier: You can can stop tomcat with -force, which will kill the tomcat process after shutdown (-force only works if CATALINA_PID is set).

export CATALINA_PID=/opt/tomcat/catalina.pid
/opt/tomcat/bin/shutdown.sh -force

(If you set CATALINA_PID in your .bashrc you don’t have to set it before startup/shutdown)

Posted in Tomcat. Tags: . 1 Comment »