Tomcat

From Omnia
Jump to navigation Jump to search

Apache Tomcat

Apache Tomcat - http://tomcat.apache.org/

Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed under the Java Community Process.

Installing Tomcat

Package Manager

Yum:

yum install tomcat5

Apt:

apt-get install tomcat6

Manual Installation

Java

# RPM
sudo su -
cd /opt
# http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html#jdk-6u45-oth-JPR
# wget http://install.oeey.com/jdk-6u45-linux-x64-rpm.bin
wget http://install.oeey.com/jdk-6u45-linux-amd64.rpm
rpm -Uvh jdk-6u45-linux-amd64.rpm
ln -s /usr/java/jdk1.6.0_23 java
# Non-RPM
sudo su -
cd /opt
# http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html#jdk-6u45-oth-JPR
wget http://install.oeey.com/jdk-6u45-linux-x64.bin
chmod u+x jdk-6u45-linux-x64.bin
./jdk-6u45-linux-x64.bin
ln -s jdk1.6.0_45 java

Tomcat 5.5:

sudo su -
cd /opt/
wget http://apache.cs.utah.edu/tomcat/tomcat-5/v5.5.34/bin/apache-tomcat-5.5.34.tar.gz
tar -zvxf apache-tomcat-5.5.34.tar.gz
ln -s apache-tomcat-5.5.34 tomcat5

Tomcat 6: (PREFERRED)

sudo su -
cd /opt/
# wget http://apache.cs.utah.edu/tomcat/tomcat-6/v6.0.43/bin/apache-tomcat-6.0.43.tar.gz
wget http://install.oeey.com/apache-tomcat-6.0.43.tar.gz
tar -zvxf apache-tomcat-6.0.43.tar.gz
ln -s apache-tomcat-6.0.43 tomcat6
echo "export JAVA_HOME=/opt/java" >> tomcat6/bin/setenv.sh
echo "export CATALINA_HOME=/opt/tomcat6" >> ~/.bashrc

Tomcat 7:

sudo su -
cd /opt/
wget http://apache.cs.utah.edu/tomcat/tomcat-7/v7.0.22/bin/apache-tomcat-7.0.22.tar.gz
tar -zvxf apache-tomcat-7.0.22.tar.gz
ln -s apache-tomcat-7.0.22 tomcat7

Folder Structure

bin/  - management scripts
conf/  - configuration files
lib/  - libraries
logs/  - application and system logs
  - catalina.out
  - catalina.[date].log
  - houst-manager.[date].log
  - localhost.[date].log
  - manager.[date].log
temp/  - temporary artifacts from web apps
webapps/  - web applications
work/  - internal temp folder for tomcat

LICENSE
NOTICE
RELEASE-NOTES
RUNNING.txt

Startup Management

This can be done as any user, as long as the configured ports are not restricted.

Startup:

bin/startup.sh

Shutdown:

bin/shutdown.sh

Configuration

Listening Port

conf/server.xml:

<Server port="8005" shutdown="SHUTDOWN">

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

Note: If you don't need AJP, comment out the AJP connector.

Note: Change both shutdown and connector port if you wish to run multiple copies of Tomcat on the server.

Tomcat Users

There are no default users:

$CATALINA_HOME/conf/tomcat-users.xml: (with a whole bunch of comments)

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
</tomcat-users>

To access the manager add the following...

$CATALINA_HOME/conf/tomcat-users.xml:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="manager,admin"/>
</tomcat-users>

Default Application

The default application hosted in the ROOT folder. To change this, put the new app in place and restart tomcat.

webapps/ROOT

Management

Tomcat Manager

"Tomcat Web Application Manager"

Add a user with role "manger" to tomcat-users.xml and access here:

http://localhost:8080/manager/html

From here you can deploy new apps, and remove old.

Initial Cleanup

cd $CATALINA_HOME
mv webapps webapps-default
mkdir -p webapps/ROOT
echo "Hello World" > webapps/ROOT/index.html
rm -f logs/*
rm -rf work/*
rm -rf temp/*
rm -f bin/*bat
mkdir .archive
mv conf/Catalina webapps-default LICENSE NOTICE RELEASE-NOTES RUNNING.txt  .archive

Note: To remove the manager(s) logging, you will need to manually remove the 'manager' lines from conf/logging.properties. "ConsoleHandler" should also be removed.

Redirect console to specified file (in setenv.sh):

CATALINA_OUT=/opt/tomcat/logs/console.out

Note: To remove catalina.out completely, set "export CATALINA_OUT=/dev/null" in setenv.sh

Remove manager logging:

cd /opt/tomcat/conf
cp logging.properties logging.properties.original
sed -i '/^3manager/d' logging.properties
sed -i '/\/manager/d' logging.properties
sed -i '/^4host-manager/d' logging.properties
sed -i '/\/host-manager/d' logging.properties
sed -i 's/3manager.org.apache.juli.FileHandler, 4host-manager.org.apache.juli.FileHandler,//' logging.properties

Cleanup

Note: Can be done anytime Tomcat is stopped.

cd /opt/tomcat
rm -f logs/*
rm -rf work/*
rm -rf temp/*

Installation Tutorial

Installing Tomcat on Linux - Tomcat Installation on Linux - Apache Tomcat HOWTO


Application Developer's Guide - Table of Contents - http://tomcat.apache.org/tomcat-6.0-doc/appdev/index.html

  • Introduction - Briefly describes the information covered here, with links and references to other sources of information.
  • Installation - Covers acquiring and installing the required software components to use Tomcat for web application development.
  • Deployment Organization - Discusses the standard directory layout for a web application (defined in the Servlet API Specification), the Web Application Deployment Descriptor, and options for integration with Tomcat in your development environment.
  • Source Organization - Describes a useful approach to organizing the source code directories for your project, and introduces the build.xml used by Ant to manage compilation.
  • Development Processes - Provides brief descriptions of typical development processes utilizing the recommended deployment and source organizations.
  • Example Application - This directory contains a very simple, but functionally complete, "Hello, World" application built according to the principles described in this manual. You can use this application to practice using the described techniques.

Apache Tomcat Native library

Apache Portable Runtime and Tomcat - http://tomcat.apache.org/tomcat-5.5-doc/apr.html

To stop the following error from appearing...

Error:

==> catalina.out <==
Oct 22, 2011 10:08:46 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/jdk1.6.0_23/jre/lib/i386/client:/usr/java/jdk1.6.0_23/jre/lib/i386:/usr/java/jdk1.6.0_23/jre/../lib/i386:/usr/java/packages/lib/i386:/lib:/usr/lib

Dependencies:

yum -y install gcc make openssl-devel
apt-get install gcc make libssl-dev

Build APR libraries:

# BUILD APACHE PORTABLE RUNTIME
# APACHE PORTABLE RUNTIME SITE: http://apr.apache.org/
mkdir -p ~/.src ; cd ~/.src
wget http://mirror.reverse.net/pub/apache/apr/apr-1.5.1.tar.gz
tar -zvxf apr-1.5.1.tar.gz
cd apr-1.5.1
./configure --prefix=/opt/apr
make clean && make && sudo make install

Build Tomcat Native Library

# BUILD APACHE TOMCAT NATIVE LIBRARY
# APACHE TOMCAT NATIVE LIBRARY SITE: http://tomcat.apache.org/tomcat-5.5-doc/apr.html
# The wrapper library sources are located in the Tomcat binary bundle, in the bin/tomcat-native.tar.gz archive
yum -y install openssl-devel
apt-get install libssl-dev
mkdir -p ~/.src ; cd ~/.src
cp /opt/tomcat/bin/tomcat-native.tar.gz ~/.src
tar -zvxf tomcat-native.tar.gz
cd tomcat-native-1.1.32-src/jni/native
### READ "BUILDING" FOR BUILD INSTRUCTIONS
# export JAVA_HOME=/opt/java # not needed with --with-java-home= option
./configure --with-java-home=/opt/java --with-apr=/opt/apr --with-ssl=yes
make clean && make
### PRODUCES: .libs/libtcnative-1.so
### COPY LIBRARY TO SOMEWHERE IN PATH LISTED IN ERROR LOGS...
#sudo mkdir /opt/java/lib/i386
sudo cp .libs/libtcnative-1.so /opt/java/jre/lib/amd64/
### OR add to bin/setenv.sh:
  sudo cp .libs/libtcnative-1.so /opt/tomcat/lib
  CATALINA_OPTS="$CATALINA_OPTS -Djava.library.path=/opt/tomcat/lib"

Success:

==> catalina.out <==
Oct 22, 2011 10:51:44 PM org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.20.
Oct 22, 2011 10:51:44 PM org.apache.catalina.core.AprLifecycleListener init
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].

If you get the following error, you did not compile in SSL to the native library:

Oct 22, 2011 10:51:44 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: Failed to initialize the SSLEngine.

See Scalix#Tomcat_-_Apache_Tomcat_Native_library

Memory Settings

setenv.sh: (add if needed)


# not sure if this one is working correctly
CATALINA_OPTS="$CATALINA_OPTS -server -Xms1024m -Xmx3052m"
JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8\
-server -Xms1536m -Xmx1536m\
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m\
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
export JAVA_OPTS="-Xmx512m -XX:MaxPermSize=128m"

server.xml

Default server.xml

Without comments:

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JasperListener" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
      </Host>
    </Engine>
  </Service>
</Server>

Minimal server.xml

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">

	<!-- APR library loader. -->
	<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
	<!-- Initialize Jasper prior to webapps are loaded. JSP 1.2. -->
	<!-- <Listener className="org.apache.catalina.core.JasperListener" /> -->
	<!-- Prevent memory leaks due to use of particular java/javax APIs -->
	<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />


	<Service name="Catalina">

		<Connector port="8080" protocol="HTTP/1.1"
			connectionTimeout="20000" redirectPort="8443"
		/>
		<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
			maxThreads="150" scheme="https" secure="true" sslProtocol="TLSv1"
			SSLCertificateFile="/etc/t0e.pem"
			SSLCertificateKeyFile="/etc/t0e.pem"
		/>

		<Engine name="Catalina" defaultHost="localhost">
			<Host name="localhost" appBase="webapps"
				unpackWARs="true" autoDeploy="true"
				xmlValidation="false" xmlNamespaceAware="false"
			/>
		</Engine>
	</Service>
</Server>

bin/setenv.sh

JAVA_OPTS="-Djava.awt.headless=true -Xms512m -Xmx512m -XX:MaxPermSize=256m -server"
CATALINA_OPTS="$CATALINA_OPTS -Djava.library.path=/opt/tomcat/lib"
JAVA_HOME=/opt/java
CATALINA_OUT=/opt/tomcat/logs/console.out

iptables redirect

/etc/sysconfig/iptables

# Generated by iptables-save v1.3.5 on Sat Oct  8 18:41:33 2011
*filter
:INPUT ACCEPT [61:6076]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [39:8144]
COMMIT
*nat
:OUTPUT ACCEPT
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
-A PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8443
COMMIT
# Completed on Sat Oct  8 18:41:33 2011

Apache Proxy Pass

Proxy Pass to Jenkins:

NameVirtualHost *:80
<VirtualHost *:80>
    ServerName jenkins.oeey.com

    #Forwarding Traffic
    #RewriteEngine on
    #RewriteRule ^(/.*)  http://localhost:8080/$1   [P]

    # Reverse Proxy
    ProxyPass         /  http://localhost:8080/ nocanon
    ProxyPassReverse  /  http://localhost:8080/

    # Forward Proxy
    ProxyRequests     Off
    AllowEncodedSlashes NoDecode

    # Local reverse proxy authorization override
    # Most unix distribution deny proxy by default (ie /etc/apache2/mods-enabled/proxy.conf in Ubuntu)
    #<Proxy http://localhost:8080/jenkins*>
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ServerAdmin admin@oeey.com
    ErrorLog logs/jenkins.oeey.com-error_log
    CustomLog logs/jenkins.oeey.com-access_log common
</VirtualHost>

---

<VirtualHost *:80>
    ServerName oeey.com
    ServerAlias www.oeey.com

    # Reverse Proxy
    ProxyPass         /  http://localhost:8080/
    ProxyPassReverse  /  http://localhost:8080/

    ServerAdmin admin@oeey.com
    ErrorLog logs/oeey.com-error_log
    CustomLog logs/oeey.com-access_log common
</VirtualHost>

Ubuntu:

a2enmod proxy
a2enmod proxy_http
service apache2 restart


Apache Proxy Pass HTTPS

Proxy Pass to Jenkins:

NameVirtualHost *:443
<VirtualHost *:443>
    ServerName jenkins.oeey.com

    # Reverse Proxy
    ProxyPass         /  http://localhost:8080/
    ProxyPassReverse  /  http://localhost:8080/

</VirtualHost>

SSL

Apache Tomcat 6.0 - SSL Configuration HOW-TO - http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html

If the installation uses APR - i.e. you have installed the Tomcat native library - then it will use the APR SSL implementation, otherwise it will use the Java JSSE implementation.

To enable HTTPS:

  • Uncomment the "SSL HTTP/1.1 Connector" entry in $CATALINA_BASE/conf/server.xml

To disable HTTP:

  • Comment the "<Connector port="8080" protocol="HTTP/1.1"..." entry in $CATALINA_BASE/conf/server.xml

SSL with Java keystore

Tomcat currently operates only on JKS, PKCS11 or PKCS12 format keystores.

Create a keystore file to store the server's private key and self-signed certificate by executing the following command:

$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA
# use default password of 'changeit', or specify alternate in server.xml
# key password must match keystore password
# this generates ~/.keystore

To generate the keystore in an alternate location:

$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA -keystore [PATH_FOR_KEYSTORE]

Uncomment the "SSL HTTP/1.1 Connector" entry in $CATALINA_BASE/conf/server.xml

Convert OpenSSL PEM to PKCS12:

openssl pkcs12 -export -in [MYCERT.CRT] -inkey [MYKEY.KEY] -out mycert.p12 -name tomcat
openssl pkcs12 -export -in [MYCERT.CRT] -inkey [MYKEY.KEY] -out mycert.p12 -name tomcat -CAfile [MYCA.CRT] -caname root -chain

SSL with OpenSSL PEM

MUCH GOODERER!

If the installation uses APR (Tomcat native library) then it will use the APR SSL implementation.

server.xml:

<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
	
<-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<Connector 
           port="8443" maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           SSLCertificateFile="/usr/local/ssl/server.crt" 
           SSLCertificateKeyFile="/usr/local/ssl/server.key"
           SSLProtocol="TLSv1"/>

And if needed:

SSLCertificateChainFile

Note: All 3 can point to the same PEM file.

References:

Redirect HTTP to HTTPS

Change the HTTP connector to redirect to 443 in $CATALINA_BASE/conf/server.xml:

    <Connector port="80"
        enableLookups="false" redirectPort="443" ...

Add the following section to the end of $CATALINA_BASE/conf/web.xml within the <web-app> element.

    ...
    <!-- SSL settings. only allow HTTPS -->
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Entire Application</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

</web-app>

References:

Hello World

Default Welcome Page

How do I override the default home page loaded by Tomcat? - http://wiki.apache.org/tomcat/HowTo#How_do_I_override_the_default_home_page_loaded_by_Tomcat.3F

$TOMCAT_HOME/conf/web.xml:

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

Default Web Application

How do I make my web application be the Tomcat default application ? - http://wiki.apache.org/tomcat/HowTo#How_do_I_make_my_web_application_be_the_Tomcat_default_application_.3F

Replace the application under $TOMCAT_HOME/webapps/ROOT with the desired webapp

If war, rename your war to ROOT.war and deploy.

java - Tomcat 6: How to change the ROOT application - Stack Overflow - http://stackoverflow.com/questions/715506/tomcat-6-how-to-change-the-root-application

You can do this in a slightly hack-y way by:

   Stop Tomcat
   Move ROOT.war aside and rm -rf webapps/ROOT
   Copy the webapp you want to webapps/ROOT.war
   Start Tomcat

Clustering Tomcat

See Clustering Tomcat

Securing Tomcat

Securing tomcat - OWASP - https://www.owasp.org/index.php/Securing_tomcat

JSP

See JSP

hello.jsp: [1]

<html>
        <head><title>Hello World JSP Page.</title></head>
        <body>
                <font size="10"><%="Hello World!" %></font>
        </body>
</html>

Tomcat Alternatives

Jetty

"I find the Tomcat server as whole a rather messy business. I've often been displeased when perusing the source code. I see lots of arbitrary bandaid like solutions in much of Apache land. For a webserver/J2EE server, I find Jetty a cleaner implementation. Jetty is really easy to embed in applications too." -- [2]

Tomcat Performance Tuning

GZip:


Virtual Hosts

server.xml:

<Engine name="Catalina" defaultHost="apple">
    <Host name="apple"    appBase="appleapps"/>
    <Host name="orange"   appBase="orangeapps"/>
    <Host name="t0e.org"  appBase="t0eapps">
        <Context path="" docBase="ROOT"/>
        <Alias>www.t0e.org</Alias>
    </Host>
</Engine>
mkdir $CATALINA_HOME/appleapps
mkdir $CATALINA_HOME/orangeapps

# deploy ROOT.war and other WARs to $CATALINA_HOME/appleapps/
# deploy ROOT.war and other WARs to $CATALINA_HOME/orangeapps/

Context Option #1:

$CATALINA_HOME/appleapps/ROOT/META-INF/context.xml

Conext Option #2:

mkdir $CATALINA_HOME/conf/Catalina/appleapps

$CATALINA_HOME/conf/Catalina/appleapps/ROOT.xml

References:

Access Logging - Log Requests

Uncomment or add this to server.xml:

<Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>

OR

<Valve
    className="org.apache.catalina.valves.AccessLogValve"
    directory="${catalina.base}/logs"
    prefix="access_log"
    fileDateFormat="yyyy-MM-dd.HH"
    suffix=".log"
    pattern="%t %H cookie:%{SESSIONID}c request:%{SESSIONID}r  %m %U %s %q %r"
/>

References:

AJP

Apache:

LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
ProxyPass /testloadbalance/ ajp://localhost:8009/testloadbalance/

Tomcat:

<Connector port="8009" protocol="AJP/1.3" redirectPort="8080" />

Keep Alive

KeepAlive – 2 parameters

  • MaxKeepAliveRequests – max number of requests to serve before closing,
  • ConnectionTimeOut – max time to keep thread open

MaxKeepAliveRequests

  • Set to 1 for high concurrency, not using SSL
  • Set to >1 for SSL, low concurrency

ConnectionTimeout -

  • Default = 20 seconds!
  • ConnectionTimeout="20000" too high turn down to +/- 3000 – 3 seconds

References:

  • Tomcat Performance Tuning - www.jumpingbean.co.za/files/tomcat-performance-tuning-jug.pdf

init.d Startup Script

touch /etc/init.d/tomcat
chmod +x /etc/init.d/tomcat
cat > /etc/init.d/tomcat <<"EOF"
#!/bin/sh
#
# Startup script for the Tomcat Server
#
# chkconfig: 35 90 10
# description: Tomcat application server
# processname: tomcat
# pidfile: /var/run/tomcat.pid
# config:

# be sure to set up iptables:
# iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080


# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Set Tomcat environment.
export TOMCAT_USER=tomcat
export JAVA_HOME=/opt/java-latest

export CATALINA_HOME=/opt/tomcat-latest
#export CATALINA_OPTS="-server -Xms64m -Xmx512m -Dbuild.compiler.emacs=true"
#export PATH=/usr/local/j2sdk/bin:/usr/local/j2re/bin:$PATH

[ -f $CATALINA_HOME/bin/catalina.sh ] || exit 0

# See how we were called.
case "$1" in
  start)
        # Start daemon.
        echo -n "Starting Tomcat: "
        cd $CATALINA_HOME
        su -c "$CATALINA_HOME/bin/catalina.sh $1" $TOMCAT_USER
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch /var/lock/subsys/tomcat
        ;;
  stop)
        # Stop daemons.
        echo -n "Shutting down Tomcat: "
        su -c "$CATALINA_HOME/bin/catalina.sh $1" $TOMCAT_USER
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/tomcat
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  condrestart)
       [ -e /var/lock/subsys/tomcat ] && $0 restart
       ;;
  status)
        status tomcat
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac

exit 0
EOF

Startup Script #1

Tomcat init.d startup script:

#
# chkconfig: 345 91 10 
# description: Starts and stops the Tomcat daemon.
#

# Source function library.
. /etc/rc.d/init.d/functions

# Get config.
. /etc/sysconfig/network

# Check that networking is up.
[ "${NETWORKING}" = "no" ] && exit 0

tomcat=/usr/local/jakarta-tomcat
startup=$tomcat/bin/startup.sh
shutdown=$tomcat/bin/shutdown.sh
#export JAVA_HOME=/usr/local/jdk  -- i have this already....

start(){
	echo -n $"Starting Tomcat service: " 
	# Change to tomcat user to start server. Don't run as root.
	#daemon -c 
	$startup
	RETVAL=$?
	echo
}

stop(){
	action $"Stopping Tomcat service: " $shutdown	
	RETVAL=$?
	echo
}

restart(){
    stop
    start
}


# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
        # This doesn't work ;)
	status tomcat
	;;
  restart)
	restart
	;;
  *)
	echo $"Usage: $0 {start|stop|status|restart}"
	exit 1
esac

exit 0

Startup Script #2

Another simpler init.d startup script

#!/bin/bash
#
# apache
#
# chkconfig:
# description:  Start up the Tomcat servlet engine.

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


RETVAL=$?
TOMCATHOME="/usr/local/tomcat"

case "$1" in
 start)
        if [ -f $TOMCATHOME/bin/startup.sh ];
          then
            echo $"Starting Tomcat"
            /bin/su - tomcat -c $TOMCATHOME/bin/startup.sh
        fi
        ;;
 stop)
        if [ -f $TOMCATHOME/bin/shutdown.sh ];
          then
            echo $"Stopping Tomcat"
            /bin/su - tomcat -c $TOMCATHOME/bin/shutdown.sh
        fi
        ;;
 *)
        echo $"Usage: $0 {start|stop}"
        exit 1
        ;;
esac

exit $RETVAL

Startup Sript #3

Anthill startup script:

# anthill       Startup script for the Anthill
#
# httpd is 85 15
# chkconfig: - 84 16
# description: Anthill is a build manager
#

# Source function library.
. /etc/rc.d/init.d/functions

# Get config.
. /etc/sysconfig/network

# Check that networking is up.
[ "${NETWORKING}" = "no" ] && exit 0

JAVA_HOME=/usr/java/jdk1.5.0_13

TOMCAT=/opt/anthill/apache-tomcat-5.5.25
TOMCATUSER=build

# See how we were called.
case "$1" in
  start)
        echo -n $"Starting Anthill service: "
        sudo -u $TOMCATUSER sh -c "export JAVA_HOME=$JAVA_HOME ; $TOMCAT/bin/startup.sh"
        RETVAL=$?
        echo
        ;;
  stop)
        action $"Stopping Tomcat service: "
        sudo -u $TOMCATUSER sh -c "export JAVA_HOME=$JAVA_HOME ; $TOMCAT/bin/shutdown.sh"
        RETVAL=$?
        echo
        ;;
  status)
        # This doesn't work ;)
        status tomcat
        ;;
  restart)
        stop
        start
        RETVAL=$?
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac

exit $RETVAL

Startup Script #4

# tomcat -- init script
#       This is the init script for starting up the
#               Jakarta Tomcat server
#
# chkconfig: 345 91 10
# description: Starts and stops the Tomcat daemon.
#

# Source function library.
. /etc/rc.d/init.d/functions

# Get config.
. /etc/sysconfig/network

# Check that networking is up.
[ "${NETWORKING}" = "no" ] && exit 0

tomcat=/opt/extreme_apache-tomcat-5.5.23/
startup=$tomcat/bin/startup.sh
shutdown=$tomcat/bin/shutdown.sh
#export JAVA_HOME=/usr/local/jdk  -- i have this already....

start(){
        echo -n $"Starting Tomcat service: "
        # Change to tomcat user to start server. Don't run as root.
        #daemon -c
        $startup
        RETVAL=$?
        echo
}

stop(){
        action $"Stopping Tomcat service: " $shutdown
        RETVAL=$?
        echo
}

restart(){
    stop
    start
}


# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        # This doesn't work ;)
        status tomcat
        ;;
  restart)
        restart
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 1
esac

exit 0

Startup Script #5

#!/bin/sh
# chkconfig:    2345 60 90
# description:  JIRA init script

# Source function library.
. /etc/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up. If networking isn't up, don't start.  Why?
# because Jira is useless without a network connection.
[ ${NETWORKING} = "no" ] && exit 0

JAVA_HOME=/usr/java/jdk1.5.0_10
JIRA_HOME=/opt/jira
DAEMON_HOME=/$JIRA_HOME/bin
JIRA_USER=root
TMP_DIR=/var/tmp
JIRA_OPTS="-Xmx512m -Xms512m"
CLASSPATH=\
$JAVA_HOME/lib/tools.jar:\
$DAEMON_HOME/commons-daemon.jar:\
$JIRA_HOME/bin/bootstrap.jar
PID_FILE=/var/run/jira.pid

case "$1" in
  start)
    #
    # Start JIRA
    #
    echo -n "Starting Jira:"
    $DAEMON_HOME/jsvc \
    -user $JIRA_USER \
    -home $JAVA_HOME \
    -Dcatalina.home=$JIRA_HOME \
    -Djava.io.tmpdir=$TMP_DIR \
    -outfile $JIRA_HOME/logs/catalina.out \
    -errfile '&1' \
    -pidfile $PID_FILE \
    $JIRA_OPTS \
    -cp $CLASSPATH \
    org.apache.catalina.startup.Bootstrap
    #
    # To get a verbose JVM
    #-verbose \
    # To get a debug of jsvc.
    #-debug \
    RETVAL=$?
    if [ "${RETVAL}" = 0 ] ; then
      success
    else
      failure
    fi
    echo
    exit ${RETVAL}
    ;;

  stop)
    #
    # Stop JIRA
    #
    #PID=`cat /var/run/jsvc.pid`
    #kill $PID
    echo -n "Stopping Jira:"
    $DAEMON_HOME/jsvc \
      -stop \
      -pidfile $PID_FILE \
      org.apache.catalina.startup.Bootstrap
    RETVAL=$?
    if [ "${RETVAL}" = 0 ] ; then
      success
    else
      failure
    fi
    echo
    exit ${RETVAL}
    ;;

  restart)
    #
    # Restart JIRA
    #
    echo "Restarting Jira..."
    $0 stop
    sleep 5
    $0 start
    ;;

  *)
    # echo "Usage tomcat.sh start/stop"
    echo "Usage service jira \(start\|stop\|restart\)"
    exit 1
    ;;
esac

Startup Script #6

#!/bin/bash
#
# Required-Start:    $all
# Required-Stop:
# Default-Start:     99 2 3 4 5
# Default-Stop:
# Description:       Tomcat6
#

JAVA_HOME=/opt/java/

TOMCAT=/opt/tomcat6
TOMCATUSER=tomcat

case "$1" in
  start)
        echo -n $"Starting Tomcat service: "
        sudo -u $TOMCATUSER sh -c "export JAVA_HOME=$JAVA_HOME ; $TOMCAT/bin/startup.sh"
        RETVAL=$?
        echo
        ;;
  stop)
        echo -n $"Stopping Tomcat service: "
        sudo -u $TOMCATUSER sh -c "export JAVA_HOME=$JAVA_HOME ; $TOMCAT/bin/shutdown.sh"
        RETVAL=$?
        echo
        ;;
  restart)
        stop
        start
        RETVAL=$?
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit $RETVAL

Modified from Anthill startup script

Issues

Apache Tomcat Native library

Error:

==> catalina.out <==
Oct 22, 2011 10:08:46 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/jdk1.6.0_23/jre/lib/i386/client:/usr/java/jdk1.6.0_23/jre/lib/i386:/usr/java/jdk1.6.0_23/jre/../lib/i386:/usr/java/packages/lib/i386:/lib:/usr/lib

Solution:

keywords