Apache Http Server Tomcat



Attributes to values that match your Apache httpd web server's host name and port number, so that the responses from Tomcat appear to be coming from Apache httpd. For more information on. Apache Tomcat (called 'Tomcat' for short) is an open-source implementation of the Java Servlet, JavaServer Pages, Java Expression Language and WebSocket technologies. Tomcat provides a 'pure Java' HTTP web server environment in which Java code can run.

Apache HTTP Server HowTo

Introduction

This document explains how to connect Tomcat to the popular open source web server, Apache HTTP Server.You can use the connection module mod_jk with any version of Apache starting with 1.3 and any versionof Tomcat starting with (at least) 3.2.

It is recommended that you also read theWorkers HowTo documentto learn how to setup the working entities between your web server and Tomcat Engines.For more detailed configuration information consult the Reference Guide forworkers.properties,uriworkermapand Apache.

Warning: If Apache and Tomcat are configured to serve content fromthe same file system location then care must be taken to ensure that Apache isnot able to serve inappropriate content such as the contents of the WEB-INFdirectory or JSP source code. This could occur if the Apache DocumentRootoverlaps with a Tomcat Host's appBase or the docBase of any Context. It couldalso occur when using the Apache Alias directive with a Tomcat Host's appBase orthe docBase of any Context. Free live streaming software for mac.

This document was originally part of Tomcat: A Minimalistic User's Guide written by Gal Shachor,but has been split off for organisational reasons.

Document Conventions and Assumptions

${tomcat_home} is the root directory of tomcat.Your Tomcat installation should have the following subdirectories:

  • ${tomcat_home}conf - Where you can place various configuration files
  • ${tomcat_home}webapps - Containing example applications
  • ${tomcat_home}bin - Where you place web server plugins

In all the examples in this document ${tomcat_home} will be /var/tomcat3.A worker is defined to be a tomcat process that accepts work from the Apache server.

Supported Configuration

The mod_jk module was developed and tested on:

  • Linux, FreeBSD, AIX, HP-UX, MacOS X, Solaris and should work on major Unixes platformssupporting Apache 1.3 and/or 2.x
  • WinNT4.0-i386 SP4/SP5/SP6a (should be able to work with other service packs), Win2K and WinXP and Win98
  • Cygwin (until you have an Apache server and autoconf/automake support tools)
  • i5/OS V5R4 (System I) with Apache HTTP Server 2.0.58. Be sure to have the latest Apache PTF installed.
  • Tomcat 3.2 to Tomcat 8.

The mod_jk module uses the AJP protocol to send requests to the Tomcat containers.The AJP version typically used is ajp13.

Who supports AJP protocols?

Tomcat supports ajp13 since Tomcat 3.2.Others servlet engines such as Jetty or JBoss also support the ajp13 protocol

The ajp12 protocol has been deprecated and you should no longer use it.The ajp14 protocol is considered experimental.

How does it work ?

In a nutshell a web server is waiting for client HTTP requests.When these requests arrive the server does whatever is needed to serve therequests by providing the necessary content.

Adding a servlet container may somewhat change this behaviour.Now the web server needs also to perform the following:

  • Load the servlet container adaptor library and initialise it (prior to serving requests).
  • When a request arrives, it needs to check and see if a certain request belongs to a servlet,if so it needs to let the adaptor take the request and handle it.

The adaptor on the other hand needs to know what requests it is going to serve,usually based on some pattern in the request URL, and to where to direct these requests.

Things are even more complex when the user wants to set a configuration that uses virtual hosts,or when they want multiple developers to work on the same web serverbut on different servlet container JVMs.We will cover these two cases in the advanced sections.

Obtaining mod_jk

mod_jk can be obtained in two formats - binary and source.Depending on the platform you are running your web server on, a binary version of mod_jk may be available.

It is recommended to use the binary version if one is available.If the binary is not available, follow the instructionsgiven in the below 'Building mod_jk' sections for building mod_jk from source.The mod_jk source can be downloaded from a mirrorhere

The binaries for mod_jk are now available for several platforms.The binaries are located in subdirectories by platform.

For some platforms, such as Windows, this is the typical way of obtaining mod_jksince most Windows systems do not have C compilers.

For others, the binary distribution of mod_jk offers simpler installation.

For example JK 1.2.x can be downloaded from a mirrorhere (look for JK 1.2 Binary Releases). The 'JK 1.2 Binary Releases' link contains binary version for a variety ofoperating systems for both Apache 1.3 and Apache 2.x.

Installation

mod_jk requires two entities:

  • mod_jk.xxx - The Apache HTTP Server module, depending on your operating system, it will be mod_jk.so, mod_jk.nlmor MOD_JK.SRVPGM (see the build section).
  • workers.properties - A file that describes the host(s) and port(s) used by the workers (Tomcat processes).A sample workers.properties can be found under the conf directory in the source download.

Also as with other Apache modules, mod_jk should be first installed on the modules directory of yourApache HTTP Server, ie: /usr/lib/apache and you should update your httpd.conf file.

Disabling old mod_jserv

If you've previously configured Apache to use mod_jserv, remove any ApJServMount directivesfrom your httpd.conf.

If you're including tomcat-apache.conf or tomcat.conf, you'll want to remove them as well -they are specific to mod_jserv.

The mod_jserv configuration directives are not compatible with mod_jk !

Using Tomcat auto-configure

Tomcat auto-configure is deprecated and has been removed in Tomcat 7 and later.

The auto-configure works only for a single Tomcat running on the same machine where the Apache HTTP Server is running.The simplest way to configure Apache HTTP Server to use mod_jk is to turn on the Apache HTTP Server auto-configure settingin Tomcat and put the following include directive at the end of your Apache httpd.conf file(make sure you replace $TOMCAT_HOME with the correct path for your Tomcat installation:

Note: this file may also be generated as $TOMCAT_HOME/conf/auto/mod_jk.conf

This will tell the Apache HTTP Server to use directives in the mod_jk.conf-auto file inthe Apache configuration. This file is created by enabling the Apacheauto-configuration by creating your workers.properties file at$TOMCAT_HOME/conf/jk/workers.properties and adding the listener to the Engineelement in the server.xml file as per the following example.Please note that this example is specific to Tomcat 5.x, unlike other sections of this document which also apply to previous Tomcat branches.

Then restart Tomcat and mod_jk.conf should be generated. For more information onthis topic, please refer to the API documentation at theTomcat docs website.

Custom mod_jk configuration

You should use custom configuration when:

  • You couldn't use mod_jk.conf-auto since Tomcat engine isn't on the same machine that your Apache web server,ie when you have an Apache in front of a Tomcat Farm.
  • Another case for custom configuration is when your Apache is in front of many different Tomcat engines,each one having it's own configuration, a general case in ISP hosting
  • Also most Apache web masters will retain custom configuration to be able to tune the settingsto their real needs.

Simple configuration example

Here is a simple configuration:

mod_jk Directives

We'll discuss here the mod_jk directives and details behind them

Define workers

JkWorkersFile specify the location where mod_jk will find the workers definitions.

Logging

JkLogFile specify the location where mod_jk is going to place its log file.

Since JK 1.2.3 for Apache 2.x and JK 1.2.16 for Apache 1.3 this can alsobe used for piped logging:

JkLogLevelset the log level between:

  • info log will contains standard mod_jk activity (default).
  • error log will contains also error reports.
  • debug log will contains all information on mod_jk activity

info should be your default selection for normal operations.

JkLogStampFormat will configure the date/time format found on mod_jk logfile.See the mod_jk Apache HTTP Server reference for details.

You can log mod_jk information using the Apache standard module mod_log_config.The module sets several notes in the Apache notes table.Most of them are are only useful in combination with a load balancer worker.See the mod_jk Apache HTTP Server reference for details.

You can also log a request protocol in the mod_jk log file instead ofthe access log. This is not recommended and mostly a backward compatibilityfeature. The directive JkRequestLogFormat will configure the formatof this protocol. It gets configured and enabled on a per virtual host basis.See the mod_jk Apache HTTP Server reference for details.

Forwarding

The directive JkOptions allow you to set many forwarding options which will enable (+)or disable (-) following option. Without any leading signs, options will be enabled.

The four following options +ForwardURIxxx are mutually exclusive.Exactly one of them is required, a negative sign prefix is not allowed with them.The default value is 'ForwardURIProxy' since version 1.2.24.It was 'ForwardURICompatUnparsed' in version 1.2.23 and'ForwardURICompat' until version 1.2.22.You can turn the default off by switching on one of the other two options.You should leave this at it's default value, unless you have a very goodreason to change it.

All options are inherited from the global server to virtual hosts.Options that support enabling (plus options) and disabling (minus options),are inherited in the following way:
options(vhost) = plus_options(global) - minus_options(global) + plus_options(vhost) - minus_options(vhost)

Using JkOptions ForwardURIProxy, the forwarded URIwill be partially reencoded after processing inside Apache andbefore forwarding to Tomcat. This will be compatible with localURL manipulation by mod_rewrite and with URL encoded session ids.

Using JkOptions ForwardURICompatUnparsed, the forwarded URIwill be unparsed. It's spec compliant and secure.It will always forward the original request URI, so rewritingURIs with mod_rewrite and then forwarding the rewritten URIwill not work.

Using JkOptions ForwardURICompat, the forwarded URI willbe decoded by Apache. Encoded characters will be decoded andexplicit path components like '.' will already be resolved.This is less spec compliant and is not safe if you are usingprefix JkMount. This option will allow to rewrite URIs withmod_rewrite before forwarding.

Using JkOptions ForwardURIEscaped, the forwarded URI willbe the encoded form of the URI used by ForwardURICompat.Explicit path components like '.' will already be resolved.This will not work in combination with URL encoded session IDs,but it will allow to rewrite URIs with mod_rewrite before forwarding.

JkOptions RejectUnsafeURI will block allURLs, which contain percent signs '%' or backslashes 'after decoding.

Digital camera utility 5 for mac. Most web apps do not use such URLs. Using the option RejectUnsafeURI, youcan block several well known URL encoding attacks. By default, this optionis not set.

You can also realise such a check with mod_rewrite, which is more powerfulbut also slightly more complicated.

JkOptions CollapseSlashesAll is deprecated as of 1.2.44 and will beignored if used.

JkOptions CollapseSlashesUnmount is deprecated as of 1.2.44 and will beignored if used.

JkOptions CollapseSlashesNone is deprecated as of 1.2.44 and will beignored if used.

JkOptions ForwardDirectories is used in conjunction with DirectoryIndexdirective of Apache. As such mod_dir should be available to Apache,statically or dynamically (DSO)

When DirectoryIndex is configured, Apache will create sub-requests foreach of the local-url's specified in the directive, to determine if there is alocal file that matches (this is done by stat-ing the file).

If ForwardDirectories is set to false (default) and Apache doesn't find anyfiles that match, Apache will serve the content of the directory (if directiveOptions specifies Indexes for that directory) or a 403 Forbidden response (ifdirective Options doesn't specify Indexes for that directory).

If ForwardDirectories is set to true and Apache doesn't find any files thatmatch, the request will be forwarded to Tomcat for resolution. This is used incases when Apache cannot see the index files on the file system for variousreasons: Tomcat is running on a different machine, the JSP file has beenprecompiled etc.

Note that locally visible files will take precedence over theones visible only to Tomcat (i.e. if Apache can see the file, that's the onethat's going to get served). This is important if there is more then one type offile that Tomcat normally serves - for instance Velocity pages and JSP pages.

Setting JkOptions ForwardLocalAddress, you ask mod_jk to send the local addressof the Apache HTTP Server instead of remote client address. This can be used byTomcat remote address valve for allowing connections only from configured Apacheservers.

Setting JkOptions ForwardPhysicalAddress, you ask mod_jk to send thephysical peer TCP IP address as the client address. By default mod_jkuses the logical address as provided by the web server. For example the modulemod_remoteip sets the logical IP address to the client IP forwarded by proxiesin the X-Forwarded-For header.

JkOptions FlushPackets, you ask mod_jk to flush Apache's connectionbuffer after each AJP packet chunk received from Tomcat. This option can havea strong performance penalty for Apache and Tomcat as writes are performedmore often than would normally be required (ie: at the end of eachresponse).

JkOptions FlushHeader, you ask mod_jk to flush Apache's connectionbuffer after the response headers have been received from Tomcat.

JkOptions DisableReuse, you ask mod_jk to close connections immediatelyafter their use. Normally mod_jk uses persistent connections and pools idleconnections to reuse them, when new requests have to be sent to Tomcat.

Using this option will have a strong performance penalty for Apache and Tomcat.Use this only as a last resort in case of unfixable network problems.If a firewall between Apache and Tomcat silently kills idle connections,try to use the worker attribute socket_keepalive in combination with an appropriateTCP keepalive value in your OS.

JkOptions ForwardKeySize, you ask mod_jk, when using ajp13, to forward also the SSL Key Size asrequired by Servlet API 2.3.This flag shouldn't be set when servlet engine is Tomcat 3.2.x (off by default).

JkOptions ForwardSSLCertChain, you ask mod_jk, when using ajp13,to forward SSL certificate chain (off by default).Mod_jk only passes the SSL_CLIENT_CERT to the AJP connector. This is not aproblem with self-signed certificates or certificates directly signed by theroot CA certificate. However, there's a large number of certificates signed byan intermediate CA certificate, where this is a significant problem: A servletwill not have the possibility to validate the client certificate on its own. Thebug would be fixed by passing on the SSL_CLIENT_CERT_CHAIN to Tomcat via the AJP connector.
This directive exists only since version 1.2.22.

The directive JkEnvVar allows you to forward environment variablesfrom Apache server to Tomcat engine.You can add a default value as a second parameter to the directive.If the default value is not given explicitly, the variablewill only be send, if it is set during runtime.
The variables can be retrieved on the Tomcat side as request attributesvia request.getAttribute(attributeName).Note that the variables send via JkEnvVar will not be listedin request.getAttributeNames().
The variables are inherited from the global server to virtual hosts.

Assigning URLs to Tomcat

If you have created a custom or local version of mod_jk.conf-local as noted above,you can change settings such as the workers or URL prefix.

JkMount directive assign specific URLs to Tomcat.In general the structure of a JkMount directive is:

You can use the JkMount directive at the top level or inside <VirtualHost> sections of your httpd.conf file.

Configuring Apache to serve static web application files

If the Tomcat Host appBase (webapps) directory is accessible by the Apache HTTP Server,Apache can be configured to serve web application context directory static files insteadof passing the request to Tomcat.

Caution: For security reasons it is strongly recommended that JkMount is used topass all requests to Tomcat by default and JkUnMount is used to explicitlyexclude static content to be served by Apache. It should also be noted thatcontent served by Apache will bypass any security constraints defined in theapplication's web.xml.

Use Apache's Alias directive to map a single web application context directory into Apache'sdocument space for a VirtualHost:

Starting with mod_jk 1.2.6 for Apache 2.x and 1.2.19 for Apache 1.3, it's possible to exclude some URL/URI fromjk processing by setting the env var no-jk, for example with the SetEnvIf Directive.

You could use no-jk env var to fix problem with mod_alias or mod_userdirdirective when jk and alias/userdir URLs matches.

Use the mod_jk JkAutoAlias directive to map all web application context directoriesinto Apache's document space.

Attempts to access the WEB-INF or META-INF directories within a web application contextor a Web Archive *.war within the Tomcat Host appBase (webapps) directory will fail with anHTTP 403, Access Forbidden

If you encoded all your URLs to contain the session id(;jsessionid=..), and you later decide, you want tomove part of the content to Apache, you can tellmod_jk to strip off all session ids from URLs forthose requests, that do not get forwarded via mod_jk.

You enable this feature by setting JkStripSession to On.It can be enabled individually for virtual servers. The defaultvalue is Off.

Building mod_jk on Unix

The mod_jk build use the widely used configure system.

Prepare your mod_jk configure from subversion

In case you get source from subversion, ie without an existing configure script,you should have autoconf for configuration and installation.

To create the mod_jk autoconf script, you will need libtool1.5.2, automake 1.10 and autoconf 2.59 or newer. The use of more recentversions is encouraged, e.g. for reliable detection of the features ofrecent version of operating systems.

Those tools will not be required if you are just using a package downloaded from apache.org,they are only required for developers.

To create the configure script just type:./buildconf.sh

Using configure to build mod_jk

Here's how to use configure to prepare mod_jk for building, just type:

You could set CFLAGS and LDFLAGS to add some platform specifics:

LDFLAGS=-lc ./configure -with-apxs=/home2/local/apache/bin/apxs

If you want to build mod_jk for different versions of the Apache HTTP Server, like 1.3 or 2.x,you need to go through the full build process for each of them.Please note, that Apache 2.0, 2.2 or 2.4 modules are not binary compatible.You have to compile the module using the Apache version you plan to run it in.The mod_jk build directory used is 'apache-2.0' for all 2.x builds. The source codeis compatible with Apache HTTP Server 2.0, 2.2 and 2.4.

  • use configure and indicate the correct Apache HTTP Server apxs location (--with-apxs)
  • use make
  • copy the resulting mod_jk.so binary from the apache-1.3 or apache-2.0 subdirectoryto the Apache HTTP Server modules location.
  • make clean (to remove all previously compiled object files)
  • Start over with the apxs location for your next Apache HTTP Server version.

configure arguments

Apache related parameters
--with-apxs[=FILE]FILE is the location of the apxs tool. Default is finding apxs in PATH.It builds a shared Apache module. It detects automatically the Apache version.(2.x and 1.3)
--with-apache=DIRDIR is the path where Apache sources are located.The Apache sources should have been configured before configuring mod_jk.DIR is something like: /home/apache/apache_1.3.19It builds a static Apache module.
--enable-EAPIThis parameter is needed when using Apache-1.3 and mod_ssl, otherwise you will get the error message:'this module might crash under EAPI!' when loading mod_jk.so in Apache.Not needed when --with-apxs has been used
--enable-preforkIn case you build mod_jk for a multi-threaded Apache HTTP Server 2.x MPM (Multi-Processing Module),some areas of mod_jk code need to be synchronised to make it thread-safe.Because configure can not easily detect, whether your are using a multi-threaded MPM,mod_jk by default is always build thread-safe for Apache HTTP Server 2.x.If you are sure, that your MPM is not multi-threaded, you can use '--enable-prefork'to force the removal of the synchronisation code (thus increasing performance a bit).For instance, the prefork MPM is not multi-threaded. For Apache HTTP Server 1.3this flag will be set automatically.
--disable-traceWhen using log level 'trace', mod_jk traces a lot of function calls with'enter' and 'exit' log messages. Even if the log level is not 'trace',comparing the log levels to decide about logging has some performanceimpact.
If you use '--disable-trace', then the trace log code doesn't get compiledinto the module binary and you might save some cycles during execution.
Even with '--disable-trace' logging debug messages with debug log levelwill still be possible.
--enable-api-compatibilityOnly use Apache API functions available in all Apache production releasesof the chosen major Apache release branch. This improves binarycompatibility of module builds with Apache releases older than the releaseagainst mod_jk is build (only between minor Apache versions).
--enable-flockIn case the operating system supports flock system call use this flag to enable thisfaster locks that are implemented as system call instead emulated by GNU C library.
However those locks does not work on NFS mounted volumes, so you can use'--enable-flock' during compile time to force the flocks() calls.

Examples of configure use

Apache 1.3 and 2.x build./configure --with-apxs=/usr/sbin/apxs
make
cp ./apache-1.3/mod_jk.so /usr/lib/apache
make clean
./configure --with-apxs=/usr/sbin/apxs2
make
cp ./apache-2.0/mod_jk.so /usr/lib/apache2

Building mod_jk for Apache on Windows

The module was developed using Microsoft Visual C++, so having Visual Studio installedis a prerequisite if you want to perform your own build.

You can build the source using the IDE GUI, or using a purecommandline build based on nmake. The IDE build currently onlysupports building 32 Bit binaries. The nmake builds are availablefor 32 Bit and 64 Bit binaries.

The common steps for all build procedures are:

  • Set up your build environment for 32 Bits or 64 Bits.The IDE build only supports 32 Bits.
  • Download the sources as a zip file and unpack it.
  • Change directory to the ISAPI redirector source directory.
  • Set your path to the Apache web server directory in yourenvironment.
Set up 32 or 64 Bit build environmentsetenv /Release /X86or (not available for IDE build)setenv /Release /X64Download tomcat-connectors-xxx-src.zip fromhttps://tomcat.apache.org/download-connectors.cgiand unpack itunzip tomcat-connectors-xxx-src.zipChange directory to the mod_jk source directory.To build mod_jk for the Apache HTTP server 2.0, 2.2 or 2.4,use the 'apache-2.0' directory, for the oldApache HTTP server 1.3, the 'apache-1.3' directory.cd tomcat-connectors-xxx-srcnativeapache-2.0Set the environment variable 'APACHE1_HOME' resp.'APACHE2_HOME' resp. 'APACHE22_HOME' resp. 'APACHE24_HOME'to the installation path of your Apache web server.set APACHE24_HOME=D:softwareApachehttpd-2.4.16

The steps for an IDE build are then:

  • Start Visual Studio using 'start mod_jk.dsp'
  • During IDE startup choose 'Yes' in all conversion popups.
  • Next choose a Configuration form the dropdown. There are pre-definedconfigurations for debug and release builds and in the'apache-2.0' directory each of them is available as a configurationto build against the web server versions 2.0, 2.2 and 2.4.
  • Finally choose 'Build Solution' in the 'Build' menu.
The resulting file mod_jk.so (and the debug symbol filemod_jk.pdb) is located in the 'Debug' resp. 'Release' subdirectory depending on the build Configuration chosen. Forthe 'apache-2.0' module the directories are named 'Debug_20','Release_20', 'Debug_22', 'Release_22', 'Debug_24' and 'Release_24'depending on the chosen build configuration.

Alternatively the steps for an nmake commandline build are:

  • Set your target architecture to X86 or X64 by editing the 'ARCH='line in the file Makefile.vc.
  • Issue 'nmake -f Makefile.vc'
The resulting file mod_jk.so (and the debug symbol filemod_jk.pdb) is located in the 'Debug' resp. 'Release' subdirectory depending on the build Configuration chosen. Forthe 'apache-2.0' module the directories are named 'Debug_20','Release_20', 'Debug_22', 'Release_22', 'Debug_24' and 'Release_24'depending on the chosen build configuration.

Finally you need to copy the file mod_jk.so to the modules directoryof your Apache HTTP server (resp. the libexec directory for the old Apache 1.3).

For Apache HTTP Server 1.3, ApacheCore.lib is expected to exist beforelinking mod_jk will succeed.

Building mod_jk for Apache on System I - i5/OS (OS400)

Since OS400 V4R5, System I (AS/400) has used Apache 2.0 as their primary web server,replacing the old IBM web server.It's now possible to build mod_jk on System I thanks to the help of the IBMRochester Labs which has provided information and patches to adapt mod_jk to i5/OS.

You should have at least Apache 2.0.58 (product 5722DG1), a C Compiler and IFS.Apache 2.0.58 is provided with the most recent set of PTFs for the iSeries Apacheserver, which can be found at http://www.ibm.com/servers/eserver/iseries/software/http/

The all latest Apache 2 for i5/OS V5R3 (or V5R4) is now 2.0.58 (as of 2007/04/17).Be sure to have the latest PTFs loaded if you want to make use of jk 1.2.15 and higher.NB: The latest mod_jk known to work on i5/OS V5R3 was 1.2.19.

New in i5/OS V5R4, UTF is required, also for Apache modules, as such Apache modules do not requiretranslations to/from EBCDIC but works should be done to port mod_jk 1.2.23 (and higher) to V5R4.From the V5R4 Infocenter:As of i5/OS(tm) V5R4, modules must be recompiled with a UTF locale. This creates an environment where locale-dependent C runtime functions assumethat string data is encoded in UTF-8. Any hardcoded constants can be encoded in UTF-8 by adding a #pragma convert(1208) statement in the module.Additionally, input data from the client will no longer be converted to EBCDIC but will be passed as-is.Output data sent from the module is not converted either so it must be encoded in ASCII or UTF8 as required.APR and HTTP APIs as of V5R4, expect data in UTF-8. Note that several APIs have additional functions that allow a CCSID to be set toindicate the encoding of the parameters being passed. Conversion functions between UTF-8 and EBCDIC have been added.Be sure to review APIs used by your module to be aware of current changes.

To configure mod_jk on System I use the CL source provided with the mod_jk source.

  • Get the latest mod_jk source and untar it on a Windows or Unix boxes
  • Create a directory in IFS, ie /home/apache
  • Send the whole jk source directory to System I directory via FTP.
  • Then go to the System I command line:
Create mod_jk libraryCRTLIB MOD_JK TEXT(‘Apache mod'jk tomcat connector module')Create service program source fileCRTSRCPF MOD_JK/QSRVSRC TEXT(‘Service program source file’)Create the CL build program source fileCRTSRCPF FILE(MOD_JK/QCLSRC) TEXT(‘Build program source file’)Edit the service program source fileSTRSEU MOD_JK/QSRVSRC MOD_JK

In the edited file, specify that only jk_module should be exported: Columns . . : 1 71 Edit MOD_JK/QSRVSRC SEU> MOD_JK *************** Beginning of data ************************************* 0001.00 STRPGMEXP PGMLVL(*CURRENT) 0002.00 EXPORT SYMBOL('jk_module') 0003.00 ENDPGMEXP ****************** End of data ****************************************

You could start to build all the modules of mod_jk (cases for V5R4 or previous releases):

Copy the CL build program source for i5/OS before V5R4 from IFSCPYFRMSTMF FROMSTMF('/home/apache/jk/native/apache-2.0/bldjk.qclsrc') +TOMBR('/QSYS.LIB/MOD_JK.LIB/QCLSRC.FILE/BLDJK.MBR') MBROPT(*REPLACE)Build the CL build programCRTCLPGM PGM(MOD_JK/BLDJK) SRCFILE(MOD_JK/QCLSRC) TEXT('Apache mod_jk build program')Launch the buildCALL MOD_JK/BLDJK
If the build if successfull, copy the new mod_jk moduleCRTDUPOBJ OBJ(MOD_JK) FROMLIB(MOD_JK) OBJTYPE(*SRVPGM) TOLIB(QHTTPSVR) NEWOBJ(MOD_JK)
Copy the CL build program source for i5/OS V5R4 from IFSCPYFRMSTMF FROMSTMF('/home/apache/jk/native/apache-2.0/bldjk54.qclsrc') +TOMBR('/QSYS.LIB/MOD_JK.LIB/QCLSRC.FILE/BLDJK54.MBR') MBROPT(*REPLACE)Build the CL build program for i5/OS V5R4CRTCLPGM PGM(MOD_JK/BLDJK54) SRCFILE(MOD_JK/QCLSRC) TEXT('Apache mod_jk build program') TGTRLS(*CURRENT)Launch the build for i5/OS V5R4CALL MOD_JK/BLDJK54
If the build if successfull, copy the new mod_jk moduleCRTDUPOBJ OBJ(MOD_JK) FROMLIB(MOD_JK) OBJTYPE(*SRVPGM) TOLIB(QHTTPSVR) NEWOBJ(MOD_JK)

Next, you should restart your Apache 2.0 instance and enjoy this piece of OpenSource on System I.

ENDTCPSVR SERVER(*HTTP) HTTPSVR(MYSERVER)STRTCPSVR SERVER(*HTTP) HTTPSVR(MYSERVER)Https

Building mod_jk for Apache on MacOS/X

Mac OS X (10.2.x) build notes:

Assuming that you are root:

For Apache 1.3:./configure --with-apxs=/usr/sbin/apxscd apache-1.3make -f Makefile.apxscp mod_jk.so /etc/libexec/httpdFor Apache 2.x:./configure --with-apxs=/usr/local/apache2/bin/apxs(you should point to the directory where you installed Apache 2.x)cd apache-2.0make -f Makefile.apxs install

Getting mod_jk linked statically with Apache

mod_jk allows to install mod_jk in the Apache source tree to get a staticallylinked mod_jk. Having mod_jk in the Apache executable brings some small performanceimprovements. The configure option --with-apache prepare mod_jk to install itin the Apache source tree.The option --with-apache works both for Apache 1.3 and Apache 2.x.The examples below show how to get mod_jk in the Apache process.

Installation for Apache-2.x

/home/apache24/httpd-2.4.12 is the directory where the Apache HTTP Server sourcesare located. ./configure --with-apache=/home/apache24/httpd-2.4.12
make
Install the mod_jk library and other files in/home/apache24/httpd-2.4.12/modules: make install
It is not possible to configure Apache directly because the config.m4 of mod_jk mustbe added to the configure of httpd-2.x. cd /home/apache24/httpd-2.4.12sh buildconfconfigure .. --with-mod_jkmakemake install

The enable-jk=share and enable-jk=static are not supported. --with-mod_jk onlyallow static linking of mod_jk.

Installation for Apache-1.3

/home/apache/apache_1.3.27 is the directory where the apache-1.3 sourcesare located. ./configure --with-apache=/home/apache/apache_1.3.27
make
Install the libjk library, mod_jk.c, includes and other files in/home/apache/apache_1.3.27/src/modules/jk: make install
Configure in the Apache sources: cd /home/apache/apache_1.3.27configure .. --enable-module=dir --disable-shared=dir --activate-module=src/modules/jk/libjk.a --disable-shared=jkmakemake install

The --enable-shared=jk is also working and builds a dso file.

Just change the configure in the Apache sources: configure .. --enable-module=dir --enable-shared=dir --activate-module=src/modules/jk/libjk.a --enable-shared=jk

This document explains how to connect Tomcat to the popular open source web server, Apache. It was originally part of Tomcat: A Minimalistic User's Guide by Gal Shachor, but has been split off for organizational reasons. It should be considered a work in progress. Since the Tomcat source tree is constantly changing, the information herein may be out of date. The only definitive reference at this point is the source code.

Other important documents:

Table of Contents

  • Introduction
    Need for cooperation
    How will they work together?
    What's required to pull this off?
  • Running Examples
  • Configuring Tomcat
    Setting up the Contexts
    Making sure it all works
    The AJP Connector
  • Configuring Apache
    • Web Server Adapter
      mod_jk versus mod_jserv
      Where do I get them?
      How do I build them?
      Configuration implications
    • httpd.conf - Apache's main configuration file
      mod_jk.conf-auto
      tomcat-apache.conf
  • Multiple Tomcat JVMs
    Configuring Tomcat
    Configuring Apache
  • Virtual Hosting
  • Common Installation and Configuration Problems / Questions
    Requesting http://webserver:8007/ produces an HTTP 500 error
    Apache won't start when Tomcat is running / 'BindException: Address already in use'
    Apache's <Directory> and <Location> directives seemingly ignored
    Tomcat isn't receiving requests under /servlet
    How do I get Tomcat to start automatically as 'nobody'?
    Can I run both Apache/JServ and JServ/Tomcat on the same machine?
    Migrating from Apache/JServ JSSI to Apache/Tomcat
    mod_jk - I want to use it, but I can't find it. Where is it?
    mod_jk - Apache locks up when requesting a Servlet or JSP
    mod_rewrite - Used to work fine with Apache/JServ, what gives?
    mod_ssl - pages sometimes don't finish loading using Internet Explorer
    mod_ssl - getScheme() always returns HTTP!

Introduction

Need for cooperation

As stated in the Tomcat User's Guide, Tomcat currently supports three modes of execution. While it is entirely possible to have Tomcat serve both your static and dynamic document provision needs, there are several reasons why you might not want want to do this. With respect to the Apache web server,

1. Tomcat is not as fast as Apache when it comes to static pages.
2. Tomcat is not as configurable as Apache.
3. Tomcat is not as robust as Apache.
4. Tomcat may not address many sites' need for functionality found only in Apache modules (e.g. Perl, PHP, etc.).

For all these reasons it is recommended that real-world sites use an industrial-strength web server, such as Apache, for serving static content, and use Tomcat as a Servlet/JSP add-on.

How will they work together?

In a nutshell a web server is waiting for requests. When these requests arrive the server does whatever is needed to serve the requests by providing the necessary content. Adding Tomcat to the mix may somewhat change this behavior. Now the web server needs to perform the following:

  • Before the first request can be served, Apache needs to load a web server adapter library (so Tomcat can communicate with Apache) and initialize it.
  • When a request arrives, Apache needs to check and see if it belongs to a servlet; if so it needs to let the adapter take the request and handle it.

We'd like Apache to handle our static content, such as images and HTML documents, and forward all requests for dynamic content to Tomcat. More specifically, we need answers to the following questions:

1. How will Apache know which request / type of requests should be forwarded to Tomcat?
2. How will Apache forward these requests to Tomcat?
3. How will Tomcat accept and handle these requests?

The majority of our time will be spent dealing with points 1 and 2; 3 should be a snap!

What's required to pull this off?

Answers to the above three questions!

1. Modify Apache's httpd.conf file.
2. Install a web server adapter.
3. Modify Tomcat's server.xml file.

It is assumed that you are comfortable modifying the configuration of Tomcat and Apache separately before you've attempted to integrate the two. As such, we speak in Tomcat/Apache/Servlet lingo, not pausing to explain what's already been taught in their respective user guides. Details on Tomcat setup can be found in the Tomcat User's Guide, while Apache configuration information can be found in the Apache User's Guide.

Running Examples

Throughout this document, we'll refer back to these examples, as these run the gambit of the commonly-desired Apache installs.

Non-virtual Hosts

1. All JSP and Servlet requests consisting of http://localhost/ are sent to the 'rootExample' Context.
2. All JSP and Servlet requests consisting of http://localhost/subdirExample/ are sent to the 'slifkaExample' Context.

Virtual Hosts
3. All JSP and Servlet requests consisting of http://virtualhost/ are sent to 'vhostExample' Context.
4. All JSP and Servlet requests consisting of http://virtualhost/vhostSubdir/ are sent to the 'vhostSubdir' Context.

As part of all of these configurations, servlets will be mounted as well. To reach a servlet registered via a particular Context's WEB-INF/web.xml file, we'll configure it so that appending /servlet/registeredServletName to the URL does the trick. For Example (2), let's say we had the following as part of our web.xml for this context:

<servlet>
<servlet-name>SlifkaWorld</servlet-name>
<servlet-class>foo.bar.baz.SomeClass</servlet-class>
<init-param>
<param-name>someParameter</param-name>
<param-value>A value</param-value>
</init-param>
</servlet>

To reach this servlet, we would request: http://localhost/subdirExample/servlet/SlifkaWorld

If you're unsure as to what web.xml, Contexts, servlets, or webapps are, then you probably haven't read through the Tomcat User's Guide. Get to it!

Configuring Tomcat

We can configure Tomcat independantly of the other two items on our to-do list. At this point, we're assuming that you've followed the directions in the User's Guide and have Tomcat up and running in stand-alone mode.

Setting up the Contexts

First off, let's explicitly define our example Contexts in Tomcat's server.xml. The numbers preceding each configuration snippet refer to the aforementioned Running Examples.

1. <Context path='/'
docBase='webapps/rootExample'/>
2. <Context path='/slifkaExample'
docBase='webapps/slifkaExample'/>

Example (3) must be placed inside a <Host> element in server.xml. This is because a <Context> with the same path attribute exists already; Example (1) is located at '/' as is (3). We place (4) inside the <Host> element as well, because we only want it to be accessible when people specify this virtual host in the request. For more information on the <Host> element, see the server.xml section of the User's Guide, and the Virtual Hosting section below.

Remember to omit the numbers 3 and 4 if you plan on pasting this in!

<Host name='fully-qualified name or IP of the virtual host'>
3. <Context path='/'
docBase='webapps/vhostExample'/>
4. <Context path='/vhostSubdir'
docBase='webapps/vhostSubdir'/>
</Host>

After you've made the appropriate changes to server.xml, remember to restart Tomcat.

Making sure it all works

Where do we stand now? So far it's just a normal Tomcat install, which you should be well-familiar with by now from the User's Guide. Tomcat should be serving all the documents, both static and dynamic, for all of your Contexts. An easy way to see which Contexts are serving which requests is to watch your Tomcat log output, either via stdout/err or the log file.

The AJP Connector

Before we leave this section, there's one more Tomcat aspect to discuss, the AJP <Connector> element in server.xml. This is the mechanism by which Tomcat will communicate with Apache.

<!-- Apache AJP12 support. This is also used to shut down tomcat. -->
<Connector className='org.apache.tomcat.service.PoolTcpConnector'>
<Parameter name='handler'
value='org.apache.tomcat.service.connector.Ajp12ConnectionHandler'/>
<Parameter name='port'
value='8007'/>
</Connector>

To ensure that it is indeed listening on that port, Telnet to it or HTTP request it. The Ajp12ConnectionHandler will throw an exception (visible in the tomcat log file), and you'll know it's listening. As far as the web server adapter goes, this is all you really need to know on the Tomcat side for now.

Tomcat also supports AJP v1.3 via the Ajp13ConnectionHandler. We'll get to this when we discuss mod_jk and mod_jserv later on.

The Web Server Adapter

The next step in integrating Apache with Tomcat is to install a web server adapter. This is the piece of software that will relay information between Tomcat and Apache. It doesn't really belong under Apache configuration, and it doesn't really belong under Tomcat configuration, but it's required for both of them to work together.

The web server adapter answers question 2 posed above, 'How will Apache forward these requests to Tomcat?'

mod_jk versus mod_jserv

Currently there are two adapters available - jk and JServ.

Taken from our, 'mod_jk HOWTO',

mod_jk is a replacement to the elderly mod_jserv. It is a completely newTomcat-Apache plugin that passed adaptation to Tomcat. With some luck, workingwith it is going to be simpler for everyone. Here are some things to consider:

  • mod_jserv was too complex because it supported JServ specific requirements that Tomcat does not pose.
  • mod_jserv supported only Apache; on the other hand Tomcat supports many web servers through a compatibility layer named the jk library. Supporting two different modes of work became problematic in terms of support, documentation and bug fixes. mod_jk should fix that.
  • The layered approach provided by the jk library makes it easier to support both Apache1.3.x and Apache2.xx.
  • mod_jserv only supports AJP v1.2. JServ is feature complete, and won't be enhanced aside from bug fixes.
  • mod_jk supports
    • AJP v1.3 - reuse the TCP connection between Apache and Tomcat, much faster.
    • JNI - the fastest if you have a multithreaded server like Apache 2.0.

Where do I get them?

Binaries are available for Linux and Win32 under the bin directory where you obtained the Tomcat distribution file. For Linux, JServ is available as mod_jserv.so and Jk is available as mod_jk.so. For Win32, JServ is available as ApacheModuleJServ.dll and Jk is available as mod_jk.dll.

For UNIX, JServ and Jk must be build from source. Source is available as part of the Tomcat source distribution. JServ source is found in the src/native/apache/jServ directory, which contains make files for UNIX and Win32. Jk source is found in src/native/jk plus src/native/apache1.3 or src/native/apache2.0 depending on which Apache is the target. Jk make files for FreeBSD, Linux, Netware, and Win32 (as a Visual C++ 6 project file) are found in the apache1.3 and apache2.0 directories.

How do I build them?

The make files for JServ contain a small amount of documentation within. A little more can be found in User's Guide. What we have below serves as a brief treatment of the mod_jk build steps for Win32 and *nix. This is by no means meant to be a complete treatment of the build process in all environments, just a quick hit to get you started.

Win32 (an excerpt from our mod_jk HOWTO):

The redirector was developed using Visual C++ Ver.6.0, so having thisenvironment is a prereq if you want to perform a custom build. The steps that you need to take are:

  1. Change to the desired Apache (as explained above) source directory.
  2. Set an APACHE1_HOME environment variable which points to where your Apache is installed.
  3. Execute the following command:

    MSDEV mod_jk.dsp /MAKE ALL
    NOTE: If msdev is not in your path, enter the full path to msdev.exe. Also, ApacheCore.lib is expected to exist in the APACHE1_HOMEsrcCoreD and APACHE1_HOMEsrcCoreR directories before linking will succeed. You will need to build enough of the Apache source to create these libraries.
  4. Copy mod_jk.dll to Apache's modules directory.

This will build both release and debug versions of the redirector plugin (mod_jk). An alternative will be to open mod_jk.dsp in msdev and build it using the buildmenu.

UNIX:

  1. Change to the desired Apache (as explained above) source directory.
  2. Set the environment variable $APACHE_HOME to the root of the Apache source tree.
  3. Execute the following command:
    ./build.sh

That's it!

Tomcat Vs Apache Web Server

Configuration implications

The effects we're concerned with relate to the different Apache directives each adapter makes available to us. Conceptually, we'll be adding Apache directives to get the same job done, but depending on which adapter you've chosen, they will differ. We will take both adapters into consideration while explaining the Apache configuration in subsequent sections.

httpd.conf - Apache's main configuration file

Now that we've answered questions (2) and (3), we're ready to dive into question (1) - Apache itself. We need to tell Apache how to load and initialize our adapter, and that certain requests should be handled by this adapter and forwarded onto Tomcat. Which requests depends on your configuration. Surprisingly enough, this part can be just as simple as the previous two, considering that (surprise!) Tomcat does most of the work for you.

Each time you start Tomcat, after it loads Contexts (both from the server.xml and automatically from $TOMCAT_HOME/webapps), it automagically generates a number of files for you. The two that we're concerned with are:

  • tomcat-apache.conf (should really be named mod_jserv.conf-auto)
  • mod_jk.conf-auto

Both of these files do exactly what we want - supplement Apache's httpd.conf file with the directives necessary to have Apache (Tomcat) serve our static (dynamic) content needs. We'll be examining each file in the coming sections. For many users, directly including one of these files in httpd.conf, depending on the adapter you're using, suffices. For example, if you're using mod_jk (which we suggest!), you would insert the following:

include /tomcat/conf/mod_jk.conf-auto

..of course substituting in the directory you've installed Tomcat into, in place of /tomcat. NOTE: These files are generated each time Tomcat starts, and a Tomcat configuration change affecting whichever file you're including necessitates an Apache restart. If you plan on customizing this file, do it elsewhere, as it is overwritten at each restart.

mod_jk.conf-auto

For now, refer to the comments in the mod_jk.conf-auto file and mod_jk HOWTO for details.

tomcat-apache.conf

This isn't nearly as verbose as the mod_jk file, and is therefore a bit trickier to read through. What you will see below is a condensed version of the .conf file generated from a server.xml containing our Running Examples. To aid in our explanation of the file's contents, we've inserted comments directly, and funked with the formatting.

Before we get started, there is one JServ directive used extensively that you should know about: ApJServMount. ApJServMount has the following syntax:

ApJServMount <URI> <Tomcat process location and context in URI format (relative or full)>

In English, this says, 'Any request that starts with <URI> should be passed on to <Tomcat process location and context> for execution.' Don't worry if it's not quite clear yet, examples follow!

This file has been modified quite a bit as the auto-generated one doesn't do exactly what we want, and isn't laden with comments :-) but it comes pretty close! With the knowledge gained thus far, this shouldn't be too much of a leap, so here goes:

Apache-Tomcat Configuration where Apache Serves the Static Content

All of the above directives, with the exception of anything prefixed by 'ApJServ' are extensively documented in the Apache User's Guide. If you find our coverage brief, please look there for the desired information.

Below, we go into further detail about each commented step:

1. Instruct Apache to load the jserv shared-object (or the NT world dll).

If the loading went well and the module came from a file named mod_jserv.c (1a) we can start with the rest of the configuration.

2. This step sets various JServ internal parameters, in order:

  • Instruct JServ not to start the Tomcat process. Automatically starting Tomcat is not implemented yet.
  • Disable the secret key challenge/response between Apache and Tomcat. Again, the secret key work is not implemented yet.
  • Instruct JServ to copy the base server mount points (see next section) in case of virtual hosting.
  • Instruct JServ to use the notice log level. Other log levels include emerg, alert, crit, error, warn, info and debug.

3. This step sets JServ's default communication parameters.

It says that the default protocol used for the communication is ajpv12 (do not mess with this one) and that the Tomcat process runs on the same machine and listens on port 8007. If you run Tomcat on a machine other than the one used for Apache you should either update your ApJServDefaultHost or use a full URL when mounting contexts (see next). Also, if you configured the Tomcat connectors to use a port other then 8007, you should update your ApJServDefaultPort or use a full URL when mounting contexts.

4. These steps 'register' (for lack of a better word) our Example (1) context w/Apache.

Most everything is explained up inside the example, but there are a few things you should know. The first is that, as you can see, contexts mounted at the root of your web (e.g. http://localhost/ versus http://localhost/myApp) server require a little more work than they would otherwise. Second, don't take anything auto-generated for granted. It's a very nice feature and works in many, many cases. Still though, you're setting up two complicated pieces of software and should probably be familiar with what it all means and why/how it all works! Tomcat has no way of knowing how you're going to 'register' the context in Apache, and does its best to guess.

5. These steps register our Example (2) context w/Apache.

There are two differences between Example (1) and Example (2)'s setup. First, since the DocumentRoot is already defined and mounted to our rootExample content (Example (1)), we use an Alias to tell Apache how to serve up our static documents. Second, we modify the ApJServMount directive to reflect the path that the context resides in (/subdirExample).

Your configuration is complete! All you have to do now is restart Apache, and you're cooking with gas.

Multiple Tomcat JVMs

Sometimes it is useful to have different contexts handled by different JVMs, for example:

  • When each context serves a different, specific task and runs on a different machine.
  • When we want to have multiple developers work on a private Tomcat process but use the same web server.
Implementing such schemes where different contexts are served by different JVMs is very easy and the following configuration file demonstrates this:

Tomcat Configuration

Here's where we have to step back to Tomcat. First, you have to be running two separate instances of Tomcat, hence the 'mutliple JVMs'. Of course, each instance of Tomcat will need its web adapter Connector listening on a unique port. You'll remember the following snippet from server.xml in our AJP section:

<!-- Apache AJP12 support. This is also used to shut down tomcat. --<
<Connector className='org.apache.tomcat.service.PoolTcpConnector'>
<Parameter name='handler'
value='org.apache.tomcat.service.connector.Ajp12ConnectionHandler'/>
<Parameter name='port'
value='8007'/>
</Connector>

The key here is that each port parameter's 'value' attribute must have a different value. To keep in sync, let's pretend that our Example (1) has its own instance of Tomcat, as does Example (2). Example(1)'s port is 8007 and Example (2)'s port is 8009; they are both running on the localhost.

NOTE: There are other changes required to run multiple instances of Tomcat (e.g. specifying different logging directories). Those changes and more are covered in the User's Guide.

Apache Configuration

We've snipped out the irrelevant sections (at least to this example) of the .conf file. The only change(s) you need to make, is to be a bit more specific when instructing the web server adapter on how to find the Tomcat process responsible for your context.

Apache-Tomcat Configuration with per Context JVM

As you can see, the key to integrating multiple instances with Apache is to specify the full URL when mounting via the ApJServMount directive. This is how you're able to tell JServ that the Tomcat processes are each listening on separate ports. If the Tomcat instances were running on separate machines, you would change the 'localhost' to the appropriate machine name in the ApJServMount directive(s).

NOTE: Your $TOMCAT_HOME/conf/tomcat-apache.conf file is overwritten each time you restart Tomcat. This configuration requires a custom tomcat-apache.conf, so making your changes to, and subsequently including, one of the auto-generated ones is a *bad idea*. Your changes will be overwritten each time Tomcat restarts.

Virtual Hosting

Once you've got Apache configured correctly with the <VirtualHost> entries (discussed in part below), getting virtual hosting working under Tomcat isn't that difficult. There are two ways achieving this:

  1. Use a different Tomcat port (and therefore multiple instances of Tomcat) between Apache and Tomcat per virtual host.
    • Advantages
      • Works in Tomcat 3.1 and 3.2
      • Because it sends calls for different Virtual Hosts to different Tomcat JVMs, this can be used to spread the load over several machines
      • Development can occur in isolation (an instance per developer) but still use the same machine, and same overall installation of Tomcat
    • Disadvantages
      • Doesn't scale well (an instance of Tomcat per virtual host is required)
      • Difficult to maintain for more than a few hosts (requires a different server.xml for each virtual host)
  2. Use the <Host> directive in Tomcats' server.xml file
    • Advantages
      • Easier to set up
      • Uses less system resources => scales much better (only one Tomcat instance, single adapter connector port)
    • Disadvantages
      • Only works under Tomcat 3.2
      • If Tomcat needs to be restarted for one virtual host, it needs to be restarted for all of them

To set up Apache and Tomcat using the first method, you need to set up a different ports for Apache and Tomcat to communicate for each host. Here's a sample Apache configuration (which uses mod_jserv):

Option 1 - Different Tomcat for each Apache Virtual Host

NOTE: Remember to set the DocumentRoot so Apache knows where to serve the static files from. In our mod_jserv and mod_jk examples, this was done by specifying an Alias since the DocumentRoot was already defined. Keep in mind that the ApJServMount is relative from the DocumentRoot. What's a DocumentRoot and what's an Alias? See the Apache User's Guide!

As you can see from the above example, using Tomcat in a virtual hosting environment isn't that different insofar as Apache is concerned. Of course, you'll need to setup the appropriate <VirtualHost> entries, but other than that, there isn't much difference. Inside each virtual host entry, you have all of your context-specific information in the usual way, and that's it really.

Here is an example setup for a machine serving virtual hosts using the second method described above.

Option 2 - Same Tomcat for all Virtual Hosts (httpd.conf)

This creates two virtual hosts, host1 and host2, both running off of the same IP - 192.168.0.1. Any requests for paths beginning with '/servlet' are passed to Tomcat for processing, as are JSP requests, providing of course that you've added the aforementioned AddType and AddHandler directives.

Next, you need to configure Tomcat's server.xml file.

Option 2 - Same Tomcat for all Virtual Hosts (server.xml)

That's it! Place your servlets in the WEB-INF/classes directory for each virtual host, restart Tomcat and Apache, and you should be away. If not, be sure to check the Common Problems section.

Common Installation and Configuration Problems

This section isn't meant to be your one-stop shop for all troubles Tomcat-Apache, but a resource for stumbling blocks common to many first-time Tomcat'ers. See the help section of the User's Guide for additional links.

One thing that many users don't recall is that there is a wealth of information to be found in the log files! Primarily, the tomcat.log file in your $TOMCAT_HOME/logs directory, or wherever you've configured it. If you want more detail, see the User's Guide for instructions on how to edit your server.xml to have more verbose logging.

In addition, the web server adapter has a log file as well. It's usually <adapter_name>.log (e.g. mod_jserv.log).

Requesting http://webserver:8007/ produces an HTTP 500 error

If this occurs, you should see a stack trace in your tomcat.log file, starting with:

HANDLER THREAD PROBLEM: java.io.IOException: Stream broken

By default, Tomcat listens for AJP connections on port 8007. AJP is a protocol used to communicate between the web server and Tomcat, not Tomcat and your browser. Many first-time users mistakenly assume that this is how you test your Tomcat installation or Tomcat-Apache integration, while this is not the case.

Apache doesn't start when Tomcat is running

Apache Http Server Vs Tomcat

This most likely means that Tomcat is trying to use a port that is already being used by someone else - usually Apache or another instance of Tomcat. By default, Tomcat's comes configured to run an HTTP server on port 8080. If you examine the supplied server.xml file, you'll see the following element:

<!-- Normal HTTP -->
<Connector className='org.apache.tomcat.service.PoolTcpConnector'>
<Parameter name='handler'
value='org.apache.tomcat.service.http.HttpConnectionHandler'/>
<Parameter name='port'
value='8080'/>
</Connector>

To disable this, just comment out the entire <Connector> element. Otherwise, just change it to a port that doesn't conflict with Apache. If you're not going to use the Tomcat HTTP server, and you probably won't be if you are reading this document, disable it.

If you're running Apache / JServ, JServ may be clashing with Tomcat on port 8007 as well.

Can I run both Apache/JServ and Apache/Tomcat on the same machine?

Apparently you can, but you'll need to use mod_jserv rather than mod_jk. As of Tomcat 3.2b2, the mod_jserv.so is the same as that used by Apache/JServ. You will need to run Apache/JServ on a different port to Tomcat, then you can control which servlet engine/container handles which requests by specifying the appropriate port via the ApJServMount directive in Apache's httpd.conf.

<Directory> and <Location> directives ignored

Apache forwards all requests underneath a mounting to Tomcat. Let's say you had the following at the root-level of your httpd.conf file. You're thinking, 'I'll forward all JSP and Servlet requests to Tomcat'. What Apache thinks is, 'I'll forward EVERYTHING to Tomcat':

Counter-intuitive Tomcat-Apache configuration


What's happened here is that the first ApJServMount is saying, 'Anything under the root '/' should be forwarded to the following Tomcat process/path for handling.' This results in requests for static documents being forwarded as well, which isn't what we want. If I was told to 'fix' the above conf file, I would just change the '/' after ApJServMount to '/servlet'. You would have already defined earlier up that all JSP requests go to the jserv-servlet handler (see our Apache-mod_jserv configuration section).

mod_ssl - pages sometimes don't finish loading using Internet Explorer

Tomcat sends data back to the browser using the Transfer-Encoding: Chunked method. This causes problems with Internet Explorer when using SSL. The solution is to make sure the first line of the returned file isn't blank.

Apache Tomcat Download

mod_ssl - getScheme() always returns HTTP!

The protocol used by mod_jserv can't identify whether a page was requested via HTTP or HTTPS. Yes, Apache/JServ did it, but that was a hack (just checked for requests on port 443). The solution is either to check for port 443 yourself, or to upgrade to mod_jk and the ajpv13 protocol. Another symptom of this is finding requests redirected to http://yourserver.com:443 rather than https://yourserver.com/.

Migrating from Apache/JServ JSSI to Apache/Tomcat

Tomcat doesn't support JSSI. Until someone writes an Interceptor to handle them, the easiest way is to convert your .jhtml files to .jsp files. Just replace:

<servlet name=myServlet>
<param name=aParam value=aValue>
</servlet>

with

<jsp:include page='/servlet/myServlet' flush='true' >
<jsp:param name='aParam' value='aValue' />
</jsp:include>

mod_rewrite - Used to work fine with Apache/JServ, what gives?

Tomcat implements the servlet specification v2.2, whereas JServ implemented version 2.1. In the newer version, there are tighter restrictions on the mapping from URL (what the user requests) to the filename (what they get). Specifically, it insists that:

Apache Http Server Tomcat Load Balancing

request URI = context path + servlet path + path info

This means that the arbitrary mappings that mod_rewrite is capable of simply won't work without breaking the Servlet specification. One solutions is to use the [R] flag on the RewriteRule directive to 'externally redirect' the request.

Tomcat isn't receiving requests under /servlet

If you have a '<Location />' directive in your httpd.conf file, this will take precedence over any ApJServMount directives. The following example won't forward '/servlet' requests to Tomcat.

ApJServMount /servlet /ROOT
<Location />
Options Indexes Multiviews
</Location>

A workaround is to use <Directory> instead of <Location>

How do I get Tomcat to start automatically as 'nobody'?

If your UNIX-style box has an 'rc.d'-style boot directory (Solaris, RedHat, etc.), then the simplest way is to create a file in the appropriate boot directory which looks something like this:

#!/bin/sh
CLASSPATH=/your/classpath/here
export CLASSPATH
su - nobody -c '/tomcat/bin/tomcat.sh $@'

You can then invoke this as /etc/rc.d/init.d/tomcat (start | stop) from your boot sequence in the same way that you start Apache (for instance).

mod_jk - I want to use it, but I can't find it. Where is it?

As of this writing (Sept. 30, 2000) mod_jk has to be built from the Tomcat source distibution.

mod_jk - Apache locks up when requesting a Servlet or JSP

mod_jk reuses the same port when talking to Tomcat, unlike mod_jserv. You'll need to restart Apache whenever you restart Tomcat.

Credits

This document was created by Gal Shachor. It was split off into a separate document and revised by Rob Slifka and Mike Bremford. Contributors, listed in alphabetical order:

  • Jonathan Bnayahu
  • Mike Bremford
  • Alex Chaffee
  • Fiona Czuczman
  • Costin Manolache
  • Chris Pepper
  • Rob Slifka
  • ..the countless many on the tomcat-dev and tomcat-user lists!

Copyright ©1999-2000 The Apache Software Foundation
Legal Stuff They Make Us Say
Contact Information