You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 45 Next »

*Originally taken from: http://wiki.apache.org/jakarta-tomcat/Tomcat/Howto*


Contents TableOfContents


How do I add a question to this page?

Anyone may edit this page to add their own content. That is why this page is part of a Wiki and not a hardcoded static file in the FAQ.

However, do not add questions without answers to this page. If you have a question about how to do something in Tomcat which has not been addressed yet, ask the [http://jakarta.apache.org/tomcat/faq/tomcatuser.html tomcat-user list]. Once you've figured out how to fix your problem, come back and update the Wiki to allow the rest of us to benefit from what you've learned!

How do I set up and run Tomcat on Macintosh OS X?

See ["TomcatOnMacOS"]

How do I set up multiple sites sharing the same war application/war file?

See CreateVirtualHosts

How do call tomcat ant tasks to deploy webapps?

See AntDeploy

How do I load a properties file?

Here are the two most popular ways::

  • Use a ResourceBundle. See the Java docs for the specifics of how the ResourceBundle class works. Using this method, the properties file must go into the WEB-INF/classes directory or in a jar file contained in the WEB-INF/lib directory.
  • Another way is to use the method getResourceAsStream() from the ServletContext class. This allows you update the file without having to reload the webapp as required by the first method. Here is an example code snippet, without any error trapping:
        // Assuming you are in a Servlet extending HttpServlet
        // This will look for a file called "/more/cowbell.properties" relative
        // to your servlet Root Context
        InputStream is = getServletContext().getResourceAsStream("/more/cowbell.properties");
        Properties  p  = new Properties();
        p.load(is);
        is.close();  


How do I use log4j for all Tomcat log output?

To have Tomcat use log4j universally, place both log4j.jar and the Jakarta commons-logging.jar into the $TOMCAT_HOME/common/lib directory. Create your log4j properties file as $TOMCAT_HOME/common/classes/log4j.properties and configure the root logger. Here is the basic log4j.properties that I used to do this myself:

log4j.rootLogger=info, R
log4j.appender.R=org.apache.log4j.ConsoleAppender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-5p %-30.30c{1} %x - %m%n

If you only need to use log4j in your own web app, just include log4j (and any log4j properties file) in your WAR file.

How do I configure Tomcat Connectors?

On the Tomcat FAQ, there is a list of Other Resources which should have information pointing you to the relevant pages.

Each connector has its own configuration, and its own set up. Check them for more information.

In particular, here are a number of locations for Tomcat Connectors:

  • [http://jakarta.apache.org/tomcat/connectors-doc/index.html Tomcat Connectors Documentation]

  • [http://jakarta.apache.org/tomcat/connectors-doc/faq.html Tomcat Connectors FAQ]

  • [http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jk2/config/apache.html Configuring Tomcat Connectors for Apache]

John Turner has an excellent page about [http://johnturner.com/howto/apache-tomcat-howto.html Using Apache HTTP with Apache Tomcat].

How do I configure Tomcat to work with IIS and NTLM?

See ["TomcatNTLM"]

Tomcat crashed! What do I do now?

These steps are in no particular order ...

1.#0 Read the Tomcat FAQ

  1. Read the Tomcat RELEASE NOTES - there is something about Linux in it
  2. First look at the stack traces. I hope a stack trace was produced before the failure aborted the JVM process. After you get a few stack traces, see if a pattern appears. Trace back to source code if needed.
  3. Patch (or unpatch!) the operating system as needed.
  4. Patch (or unpatch!) the JVM (Java Virtual Machine).
  5. Linux Problem? - read the RELEASE NOTES!
  6. Look at commercial vendor support for other servlet engines. Sometimes the problem is universal regardless of servlet engine and may be a JVM/OS/application code issue
  7. Search Google for web pages - maybe someone else had this problem. I'll bet they did.
  8. Search Google news groups
  9. If the JVM is from a commercial vendor, (eg: IBM, HP) check their release notes and news groups
  10. Using a database? Make sure JDBC type 4 drivers are used. Check their release notes.
  11. Tweak JVM memory parameters. Setting memory too high can be as bad as having memory too low. If your memory settings are set too high, Java 1.3 JVMs may freeze while waiting for the entire garbage collection to finish. Also if the JVM has too much memory, if may be starving other resources on the machine which are needed which may be causing unforeseen exceptions. In a nutshell, throwing more memory doesn't always solve the problem!
  12. Turn off the Java JIT compiler. See the Java Docs on how to do this.


How do I share sessions across web apps?

You cannot share sessions directly across web apps, as that would be a violation of the Servlet Specification. There are workarounds, including using a singleton class loaded from the common classloader repository to hold shared information, or putting some of this shared information in a database or another data store. Some of these approaches have been discussed on the [http://jakarta.apache.org/tomcat/faq/tomcatuser.html tomcat-user mailing list], whose archives you should search for more information.

Sharing sessions across containers for clustering or replication purposes is a different matter altogether.

Why doesn't the netbeans example build for me?

I have found two issues with the build.xml provided here: http://jakarta.apache.org/struts/faqs/netbeans.html

First, add this to the top of your properties:

<property environment="env" />

Next find this line in the "war" target:

<classes dir="${build.dir}" includes="**/*.properties" />

Change it so it reads like this:

<classes dir="${src.dir}" includes="**/*.properties" />

Now it will work!

I'm encountering classloader problems when using JNI under Tomcat

The important thing to know about using JNI under Tomcat is that one cannot place the native libraries OR their JNI interfaces under the WEB-INF/lib or WEB-INF/classes directories of a web application and expect to be able to reload the webapp without restarting the server. The class that calls System.loadLibrary(String) must be loaded by a classloader that is not affected by reloading the web application itself.

Thus, if you have JNI code that follows the convention of including a static initilaizer like this:

class FooWrapper {
    static {
        System.loadLibrary("foo");
    }

    native void doFoo();
  }

then both this class and the shared library should be placed in the $CATALINA_HOME/shared/lib directory.

Note that under Windows, you'll also need to make sure that the library is in the java.library.path. Either add %CATALINA_HOME%\shared\lib to your Windows PATH environment variable, or place the DLL files in another location that is currently on the java.library.path. There may be a similar requirement for UNIX based system (I haven't checked), in which case you'd also have to add $CATALINA_HOME/shared/lib to the PATH environment variable. (Note: I'm not the original author of this entry.)

The symptom of this problem that I encountered looked something like this -

    java.lang.UnsatisfiedLinkError: Native Library WEB-INF/lib/libfoo.so already loaded in another classloader
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1525) 

How can I access members of a custom Realm or Principal?

When you create a custom subclass of RealmBase or GenericPrincipal and attempt to use those classes in your webapp code, you'll probably have problems with ClassCastException. This is because the instance returned by request.getUserPrincipal() is of a class loaded by the server's classloader, and you are trying to access it through you webapp's classloader. While the classes maybe otherwise exactly the same, different (sibling) classloaders makes them different classes.

This assumes you created a MyPrincipal class, and put in Tomcat's server/classes (or lib) directory, as well as in your webapp's webinf/classes (or lib) directory. Normally, you would put custom realm and principal classes in the server directory because they depend on other classes there.

Here's what you would like to do, but it throws ClassCastException:

MyPrincipal p = request.getUserPrincipal();
String emailAddress = p.getEmailAddress();

Here are 4 ways you might get around the classloader boundary:

1) Reflection

Principal p = request.getUserPrincipal();
String emailAddress = p.getClass().getMethod("getEmailAddress", null).invoke(p, null);

2) Move classes to a common classloader

You could put your custom classes in a classloader that is common to both the server and your webapp - e.g., either the "common" or bootstrap classloaders. To do this, however, you would also need to move the classes that your custom classes depend on up to the common classloader, and that seems like a bad idea, because there a many of them and they a core server classes.

3) Common Interfaces

Rather than move the implementing custom classes up, you could define interfaces for your customs classes, and put the interfaces in the common directory. You're code would look like this:

public interface MyPrincipalInterface extends java.security.Principal {
  public String getEmailAddress();
}

public class MyPrincipal implements MyPrincipalInterface {
...
  public String getEmailAddress() {
    return emailAddress;
  }
}

public class MyServlet implements Servlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    MyPrincipalInterface p = (MyPrincipalInterface)request.getUserPrincipal();
    String emailAddress = p.getEmailAddress();
...
}

Notice that this method gives you pretty much the webapp code you wanted in the first place

4) Serializing / Deserializing

You might want to try serializing the response of 'request.getUserPrincipal()' and deserialize it to an instance of [webapp]MyPrincipal.

Setting up SSL

Threads from the [http://jakarta.apache.org/tomcat/faq/tomcatuser.html tomcat-user list]

Using Verisign:

Using ["OpenSSL"]:

A description of "what SSL is all about anyway":


How do I set up another tomcat service on Windows, sharing the same Tomcat Home ?

This script sets up a a tomcat base directory and calls tomcat5.exe to create a windows service which will use the tomcat home given for the binaries and tomcat base you create See ["TomcatCreateWindowsService"]

How do I install Tomcat as a service under Unix?

Create a shell program to start Tomcat automatically. Each UNIX varies in how it starts up automatic services, but there are two main variants:

BSD::In a typical BSD system, there are a series of start up scripts in /etc starting with rc.. Look for, or create, a file called /etc/rc.local and enter the appropriate instructions to start up Tomcat there as a shell script.

System V::In a typical UNIX System V setup, there is a directory containing startup scripts, and other directories which contain links to these startup scripts. Create the appropriate startup script for your setup, then create the appropriate links.

For more information on each, check your system documentation.

(lightbulb) It also makes a lot of sense to use the JavaServiceWrapper.

How do I get direct access to a Tomcat Realm?

Credit: This code is from a post by Yoav Shapira http://www.yoavshapira.com in the user list

Sometimes access directly into the Tomcat realm object is needed; to do, this the following code can be used. Be aware, however, that by using this, your application is relying on a Tomcat extension and is therefore non-standard.

Note that in order for this to work the Context of the web application in question needs to have its privileged attribute set to "true", otherwise web apps do not have access to the Tomcat classes.

Server server = ServerFactory.getServer();
//Note, this assumes the Container is "Catalina"
Service service = server.findService("Catalina");
Engine engine = (Engine) service.getContainer();
Host host = (Host) engine.findChild(engine.getDefaultHost());
//Note, this assumes your context is "myContext"
Context context = (Context) host.findChild("myContext");
Realm realm = context.getRealm();

How do I make Tomcat startup faster?

See ["HowTo/FasterStartUp"]

How do I contribute to Tomcat's documentation?

  • Download the source bundle or grab the source XML file from CVS. The docs are in the jakarta-tomcat-catalina CVS module, in the webapps/docs subdirectory. They are in XML format and get processed into the HTML documentation as part of the Tomcat release.
  • Edit the documentation XML file(s) as you wish. The xdocs format is self-explanatory: use normal HTML markup, and add <section> or <subsection> tags as you see fit. Look at the existing docs as exampels. Make sure you use valid XML markup.
  • Open a Bugzilla enhancement item with the explanation of your enhancements, and attach a diff -u format of your patch. We will evaluate and commit your patch as needed. Note that the Tomcat web site is updated with every release, so that documentation changes will not be visible as soon as you submit your Bugzilla item.
  • If you're interested in previewing your changes, you will need to follow the directions for building Tomcat yourself. The docs will be generated in the webapps/tomcat-docs directory just like with any normal Tomcat distributions.
  • If you'd like to get documentation up and visible to the world before the next Tomcat release, use this wiki site.

How do I override the default home page loaded by Tomcat?

After successfully installing Tomcat, you usually test it by loading http://localhost:8080 . The contents of that page are compiled into the index_jsp servlet. The page even warns against modifying the index.jsp files for this reason. Luckily, it is quite easy to override that page. Inside $TOMCAT_HOME/conf/web.xml there is a section called <welcome-file-list> and it looks like this:

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

The default servlet attempts to load the index.* files in the order listed. You may easily override the index.jsp file by creating an index.html file at $TOMCAT_HOME/webapps/ROOT. It's somewhat common for that file to contain a new static home page or a redirect to a servlet's main page. A redirect would look like:

<html>

<head>
<meta http-equiv="refresh" content="0;URL=http://mydomain.com/some/path/to/servlet/homepage/">
</head>

<body>
</body>

</html>

This change takes effect immediately and does not require a restart of Tomcat.

How do I redirect System.out and System.err to my web page?

I have met a situation where I needed to redirect a portion of standard ouput (System.out, STDOUT) and standard error (System.err, STDERR) to my web page instead of a log file. An example of such an application is a compiler research platform that our resarch team is putting online for anybody to be able to quickly compile-test their programs on line. Naturally, the compilers dump some of their stuff to STDERR or STDOUT and they are not web application .jar. Thus, I needed badly these streams related to the compiler output to be redirected to my web editor interface. Having found no easy instructions on how to do that lead me writing up this quick HOWTO. The HOWTO is based on Servlets, but similar arrangements can be done for JSPs. The below example shows the essentials, with most non-essentials removed.

public class WebEditor
extends HttpServlet
{
 ...
	public void doGet
	(
		HttpServletRequest poHTTPRequest,
		HttpServletResponse poHTTPResponse
	)
	throws IOException, ServletException
	{
		poHTTPResponse.setContentType("text/html");

		ServletOutputStream out = poHTTPResponse.getOutputStream();

		out.println("<html>");
		out.println("<body>");
		out.println("<head>");
		out.println("<title>WebEditor Test $Revision: 1.6 $</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h3>WebEditor Test $Revision: 1.6 $</h3>");
		out.println("<hr />");

		// Backup the streams
		PrintStream oStdOutBackup = System.out;
		PrintStream oStdErrBackup = System.err;

		// Redired STDOUT and STDERR to the ServletOuputStream
		System.setOut(new PrintStream(out));
		System.setErr(new PrintStream(out));


		try
		{
			// ... call compiler here that produces
			// tons of STDOUT/STDERR messages ...
		}
		catch(Exception e)
		{
			out.println(e.toString());
		}

		// Restore original STDOUT and STDERR
		System.setOut(oStdOutBackup);
		System.setErr(oStdErrBackup);

		out.println("<hr />");
		out.println("</body>");
		out.println("</html>");
	}
}

A few caveats arise, as for instance while the System.out and System.err are deirected as per above, no logging of these is done to files. You will need more legwork to do to make the additional logging. It is important to backup and restore the original streams as the above example does. Also, notice the use of getOutputStream():
when this method is called, the getWriter() method can no longer be used in the same response object.

Corrections and comments are most welcome!

How to run Tomcat without root priviledges?

Is there a way to allow normal user(non-root) to start/stop the tomcat server. Tried assigning permision, did not work. Read thru some articles, stated that only root has permission to port below 1025. How can i allow a non-root user to do so ? thks in adv. (smile)

  • malathi ranjit singh----

One way is to put Apache httpd with mod_jk before your Tomcat servers, and use ports >=1024 in the Tomcat(s). Since we do it that way, it's the only way I know.

BTW, you should read the 1st howto. (wink)


  • A another way is to use Iptables to redirect Port 80 and 443 to user ports (>1024)
  • /sbin/iptables -A FORWARD -p tcp --destination-port 443 -j ACCEPT
  • /sbin/iptables -t nat -A PREROUTING -j REDIRECT -p tcp --destination-port 443 --to-ports 8443
  • /sbin/iptables -A FORWARD -p tcp --destination-port 80 -j ACCEPT
  • /sbin/iptables -t nat -A PREROUTING -j REDIRECT -p tcp --destination-port 80 --to-ports 8080

/sbin/iptables-save or /etc/init.d/iptables save


BSD-based Unix systems such as Mac OS X use a tool similar to iptables, called ipfw (for Internet Protocol Fire Wall). This tool is similar in that it watches all network packets go by, and can apply rules to affect those packets, such as "port-forwarding" from port 80 to some other port such as Tomcat's default 8080. The syntax of the rules is different than iptables, but the same idea. For more info, google and read the man page. Here is one possible rule to do the port-forwarding:

sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in

How do I debug a Tomcat application?

There is nothing magical about debugging a Tomcat application. All you need is an IDE and two environment variables.

  • If you have not already done so begin by creating a new Tomcat context for your application. Navigate to TOMCAT_HOME\conf\Catalina\localhost and create a new file, say, myapp.xml. This will become part of your url, so to access your app you'll have to type *http://localhost:8080/myapp*.
  • Enter the following in myapp.xml:
<Context docBase="c:/worskpace/myapp/WebRoot" path="/HelloWorld"/>

This assumes you have a web application containing WEB-INF in c:/workspace/myapp/WebRoot

  • Create two environment variables:
C:\>set JPDA_ADDRESS=1044
C:\>set JPDA_TRANSPORT=dt_socket
  • Now, you can launch Tomcat with these debug options:
TOMCAT_HOME\bin\>catalina jpda start
  • Use your IDE to connect to Tomcat through port 1044

If Eclipse happens to be your IDE of choice, you can get more information at [http://jroller.com/page/gursesl/cleanfulltext/remote_application_debugging_with_weblogic Remote Debugging with Eclipse].

How do I enable Server Side Includes (SSI)?

two things have to be done for tomcat to aknowledge SSI scripts:

  1. Rename $CATALINA_BASE/server/lib/servlets-ssi.renametojar to $CATALINA_BASE/server/lib/servlets-ssi.jar.

2. Uncomment the section of web.xml found in $CATALINA_BASE/conf/web.xml that deals with SSI. it looks like this when it is uncommented:

    <servlet>
        <servlet-name>ssi</servlet-name>
        <servlet-class>
          org.apache.catalina.ssi.SSIServlet
        </servlet-class>
        <init-param>
          <param-name>buffered</param-name>
          <param-value>1</param-value>
        </init-param>
        <init-param>
          <param-name>debug</param-name>
          <param-value>0</param-value>
        </init-param>
        <init-param>
          <param-name>expires</param-name>
          <param-value>666</param-value>
        </init-param>
        <init-param>
          <param-name>isVirtualWebappRelative</param-name>
          <param-value>0</param-value>
        </init-param>
        <load-on-startup>4</load-on-startup>
    </servlet>

additional information can be found at:
[http://tomcat.apache.org/tomcat-5.5-doc/ssi-howto.html]

How do I connect to a Websphere MQ (MQ Series) server using JMS and JNDI?

Basically, this works just as described in
[http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html]: Within your application, you are using the standard JNDI and JMS API calls. In web.xml (the container independent application descriptor), you specify resource references (stub resources). And in context.xml (the container specific application descriptor), you are actually configuring the JMS connection.

More to the point. Here's some example code, which might be added to a Servlet. The example is sending a message to an MQ server:

    import javax.jms.Queue;
    import javax.jms.QueueConnection;
    import javax.jms.QueueConnectionFactory;
    import javax.jms.QueueSender;
    import javax.jms.QueueSession;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.Context;
    import javax.naming.InitialContext;

    Context ctx = (Context) new InitialContext().lookup("java:comp/env");
    QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup("jms/MyQCF");
    QueueConnection qc = qcf.createQueueConnection();
    Queue q = (Queue) ctx.lookup("jms/MyQ");
    QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    TextMessage tm = qs.createTextMessage();
    tm.setText("Hi, there!");
    QueueSender sender = qc.createSender();
    sender.send(tm);
    sender.close();
    qs.close();
    qc.close();

Note the following:

  1. I have intentionally omitted proper resource handling. For example, one ought to ensure that qc.close() is always called by using a try { .. } finally { ..} block.

2. The code contains absolutely no references to com.ibm.mq*.jar.

3. There are only two items, which need configuration: "jms/MyQCF", and "jms/MyQ". We'll find them again in web.xml, and context.xml.

We have now written the code. Additionally, our web application needs the following files, and directories:

    +--META-INF
    |  +--- context.xml
    +--WEB-INF
       +--- web.xml
       +--- lib
            +--- com.ibm.mq.jar
            +--- com.ibm.mqjms.jar
            +--- connector.jar
            +--- geronimo-j2ee-management_1.0_spec-1.0.jar
            +--- geronimo-jms_1.1_spec-1.0.jar

The application descriptor web.xml looks just the same as usual, with the exception of the following lines:

  <resource-env-ref>
    <resource-env-ref-name>jms/MyQCF</resource-env-ref-name>
    <resource-env-ref-type>javax.jms.QueueConnectionFactory</resource-env-ref-type>
  </resource-env-ref>

  <resource-env-ref>
    <resource-env-ref-name>jms/MyQ</resource-env-ref-name>
    <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
  </resource-env-ref>

This is simply telling, that the items "jms/MyQCF", and "jms/MyQ" exist, and are instances of QueueConnectionFactory, and Queue, respectively. The actual configuration is in context.xml:

   <Resource
      name="jms/MyQCF"
      auth="Container"
      type="com.ibm.mq.jms.MQQueueConnectionFactory"
      factory="com.ibm.mq.jms.MQQueueConnectionFactoryFactory"
      description="JMS Queue Connection Factory for sending messages"
      HOST="<mymqserver>"
      PORT="1414"
      CHAN="<mychannel>"
      TRAN="1"
      QMGR="<myqueuemanager>"/>
   <Resource
      name="jms/MyQ"
      auth="Container"
      type="com.ibm.mq.jms.MQQueue"
      factory="com.ibm.mq.jms.MQQueueFactory"
      description="JMS Queue for receiving messages from Dialog"
      QU="<myqueue>"/>

Basically, you just have to enter your values for <myqserver> (the WebSphere MQ servers host name), <mychannel> (the channel name), <myqueuemanager> (the queue manager name), and <myqueue> (the queue name). Both these values, the associated names (HOST, PORT, CHAN, ...), and their collection is truly MQ specific. For example, with ActiveMQ, you typically have a broker URL, and a broker name, rather than HOST, PORT, CHAN, ...

The main thing to know (and the reason why I am writing this, because it took me some hours to find out): How do I know the property names, their meaning, and possible values? Well, there is an excellent manual, called "WebSpere MQ Using Java". It should be easy to find by entering the title into Google. The manual contains a section, called "Administering JMS objects", which describes the objects being configured in JNDI. But the most important part is the subsection on "Properties", which contains all the required details.

}}}

How do I use DataSources with Tomcat?

See UsingDataSources

How do I install the Administration web app?

If you install Tomcat 5.5 binaries, the Administration web app is not bundled with it; this describes how to add the Administration web app to your Tomcat 5.5 installation. (Tomcat 4.1 comes with the Administration web app as part of the binary).

The following refers to a Tomcat 5.5 set up on Windows 2000, so your path names will be different on *nix platforms. In this example, Tomcat 5.5.17 in installed in c:\Program Files\Apache Software Foundation\Tomcat 5.5 (this is my CATALINA_HOME).

  1. Unzip or untar (be careful to use GNU tar) the file containing the administration web app files (eg. apache-tomcat-5.5.17-admin.zip) to a temporary directory, eg. c:\temp.

  2. Copy c:\temp\apache-tomcat-5.5.17\conf\Catalina\localhost\admin.xml to the directory c:\Program Files\Apache Software Foundation\Tomcat 5.5\conf\Catalina\localhost.
  3. Copy the entire directory tree c:\temp\apache-tomcat-5.5.17\server\webapps\admin to the directory c:\Program Files\Apache Software Foundation\Tomcat 5.5\server\webapps.
  4. Add a line to your c:\Program Files\Apache Software Foundation\Tomcat 5.5\conf\tomcat-users.xml file so that you have a user who has admin role. For example, add this line just before the last line (containing </tomcat-users>) of the file:
    <user username="admin" password="makesomethingup" roles="admin,manager"/>
  5. Restart Tomcat.
  6. Now when you visit _http://localhost:8080/admin_ you should see a page that asks for a user name and password. If you still see the "no longer loaded" error message in your browser, you must either force a full reload of the web page (in Firefox, hold down Shift key while clicking on the Reload button) or just restart your browser completely.

How do I get Tomcat automatic startet as a Linux daemon?

Parts taken from the Tomcat manual...

  1. Compile and make "jsvc":
    
    cd $CATALINA_HOME/bin
    tar xvfz jsvc.tar.gz
    cd jsvc-src
    autoconf
    ./configure
    make
    cp jsvc ..
    cd ..

2. Now that "jsvc" is in your Tomcat bin-dir, you'll need a script:

#!/bin/bash

export JAVA_HOME="/PUT YOUR JAVA_HOME HERE/"
CATALINA_HOME=/PUT YOUR CATALINA_HOME HERE/
PIDFILE=/var/run/jsvc.pid

case "$1" in

  start)
    if [ -e $PIDFILE ] ; then
        echo "Tomcat already running!"
        exit 0
    else
        echo -n "Starting Tomcat                                                   "
        cd $CATALINA_HOME
        ./bin/jsvc -Djava.endorsed.dirs=./common/endorsed -cp ./bin/bootstrap.jar \
        -outfile ./logs/catalina.out -errfile ./logs/catalina.err \
        org.apache.catalina.startup.Bootstrap
        sleep 5
            if [ -e $PIDFILE ] ; then
                echo "[OK]"
                exit 0
            else
                echo "[FAIL]"
                exit 1
            fi
    fi
    ;;

  stop)
    if [ ! -e $PIDFILE ] ; then
        echo "Tomcat already stopped!"
        exit 0
    else
        echo -n "Stopping Tomcat                                                   "
        cd $CATALINA_HOME
        ./bin/jsvc -stop $PIDFILE
            if [ ! -e $PIDFILE ] ; then
                echo "[OK]"
                exit 0
            else
                echo "[FAIL]"
                exit 1
            fi
    fi
    ;;

  *)
    echo "Usage tomcat.sh start/stop"
    exit 1
    ;;
esac

3. Name this script "tomcat" and put it into your "/etc/init.d/" (don't forget to have it executable..)

4. Place symlinks to "/etc/init.d/tomcat" in the "rcX.d" - directories:

for rc0.d:   ln -s /etc/init.d/tomcat K92tomcat
for rc1.d:   ln -s /etc/init.d/tomcat K92tomcat
for rc2.d    ln -s /etc/init.d/tomcat S92tomcat
for rc3.d    ln -s /etc/init.d/tomcat S92tomcat
for rc4.d    ln -s /etc/init.d/tomcat S92tomcat
for rc5.d    ln -s /etc/init.d/tomcat S92tomcat
for rc6.d    ln -s /etc/init.d/tomcat K92tomcat

The K-letter in the linkname tells init to call the script with the argument "stop" The S-letter in the linkname tells init to call the script with the argument "start"

Check the number-part of the linkname for Apache! Mine was 91 (e.g. S91apache2). Chose one higher to get Tomcat started after Apache.

Since the script checks if Tomcat is already started, there will be no harm (smile)

That's it. Worked fine for me.

  • No labels