Apache Tomcat

From KevinWiki

(Difference between revisions)
Jump to: navigation, search
(KeyStore)
 
(13 intermediate revisions not shown)
Line 1: Line 1:
-
[[Category:Web Application Development (Java)]]
+
[[Category:Web Application Development (Java)]][[Category:Server]]
==Apache Tomcat==
==Apache Tomcat==
===Installation===
===Installation===
-Download and extract the file
-Download and extract the file
<pre>
<pre>
-
$ sudo tar -zxvf apache-tomcat-6.0.18.tar.gz  
+
$ sudo tar -zxvf apache-tomcat-7.0.34.tar.gz  
</pre>
</pre>
-create user <code>tomcat</code>
-create user <code>tomcat</code>
<pre>
<pre>
-
$ mkdir /opt/tomcat_user_home
 
$ sudo useradd -d /opt/tomcat_user_home tomcat -s /bin/bash  
$ sudo useradd -d /opt/tomcat_user_home tomcat -s /bin/bash  
 +
 +
# OR this would be better.
 +
$ sudo adduser --disabled-login --gecos 'Tomcat' --home /opt/tomcat_user_home tomcat
</pre>
</pre>
Line 26: Line 28:
<pre>
<pre>
-
$ sudo chown -R tomcat:tomcat apache-tomcat-6.0.18
+
$ sudo chown -R tomcat:tomcat apache-tomcat-7.0.33
</pre>
</pre>
<pre>
<pre>
-
$ sudo ln -s apache-tomcat-6.0.18/ tomcat  
+
$ sudo ln -s apache-tomcat-7.0.33/ tomcat  
</pre>
</pre>
Line 53: Line 55:
#!/bin/sh
#!/bin/sh
-
export JAVA_HOME=/usr/lib/jvm/java-6-sun
+
### BEGIN INIT INFO
-
# export JAVA_OPTS="-server -Xms64m -Xmx256m -XX:MaxPermSize=256m"
+
# Provides:        tomcat
 +
# Required-Start:  $network
 +
# Required-Stop:  $network
 +
# Default-Start:  2 3 4 5
 +
# Default-Stop:    0 1 6
 +
# Short-Description: Start/Stop Tomcat server
 +
### END INIT INFO
 +
 
 +
 
 +
# export JAVA_HOME=/usr/lib/jvm/java-6-sun
 +
# export JAVA_HOME=/usr/lib/jvm/java-6-openjdk
 +
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk
 +
# export JAVA_OPTS="-server -Xms64m -Xmx192m -XX:MaxPermSize=256m -XX:+DisableExplicitGC -XX:-DoEscapeAnalysis"
 +
export JAVA_OPTS="-server -Xms512m -Xmx768m -XX:MaxPermSize=384m -XX:+DisableExplicitGC -XX:-DoEscapeAnalysis"
PRG="$0"
PRG="$0"
Line 72: Line 87:
# Only set CATALINA_HOME if not already set
# Only set CATALINA_HOME if not already set
-
[ -z "$CATALINA_HOME" ] && CATALINA_HOME=`cd "$PRGDIR/.." ; pwd`
+
[ -z "$CATALINA_HOME" ] && CATALINA_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`
 +
cd /opt/tomcat_user_home
/bin/su tomcat $CATALINA_HOME/bin/catalina.sh $1
/bin/su tomcat $CATALINA_HOME/bin/catalina.sh $1
</pre>
</pre>
 +
* If <code>/dev/urandom</code> should be used instead of <code>/dev/random</code> add <code>-Djava.security.egd=file:/dev/./urandom</code> to <code>JAVA_OPTS</code>.
 +
e.g.)
 +
<pre>
 +
export JAVA_OPTS="-server -Xms512m -Xmx768m -XX:MaxPermSize=384m -XX:+DisableExplicitGC -XX:-DoEscapeAnalysis -Djava.security.egd=file:/dev/./urandom"
 +
</pre>
 +
-Make it executable (This script does not require tomcat user login to run the tomcat server. Instead, It will ask the tomcat user password when running the script).
-Make it executable (This script does not require tomcat user login to run the tomcat server. Instead, It will ask the tomcat user password when running the script).
Line 90: Line 112:
<pre>
<pre>
$ sudo chmod 755 /etc/init.d/tomcat  
$ sudo chmod 755 /etc/init.d/tomcat  
 +
</pre>
 +
Then to make it automatically start and stop when the server boots up and shuts down respectively.
 +
<pre>
sudo ln -s /etc/init.d/tomcat /etc/rc0.d/K10tomcat  
sudo ln -s /etc/init.d/tomcat /etc/rc0.d/K10tomcat  
sudo ln -s /etc/init.d/tomcat /etc/rc1.d/K10tomcat  
sudo ln -s /etc/init.d/tomcat /etc/rc1.d/K10tomcat  
Line 98: Line 123:
sudo ln -s /etc/init.d/tomcat /etc/rc5.d/S90tomcat  
sudo ln -s /etc/init.d/tomcat /etc/rc5.d/S90tomcat  
sudo ln -s /etc/init.d/tomcat /etc/rc6.d/K10tomcat  
sudo ln -s /etc/init.d/tomcat /etc/rc6.d/K10tomcat  
 +
</pre>
 +
OR
 +
<pre>
 +
$ cd /etc/init.d
 +
$ update-rc.d tomcat defaults
</pre>
</pre>
Line 109: Line 139:
http://www.jguru.com/faq/view.jsp?EID=425628
http://www.jguru.com/faq/view.jsp?EID=425628
-
 
-
 
=== Configuration ===
=== Configuration ===
Line 338: Line 366:
<source lang="bash">
<source lang="bash">
$ cd ~/.tomcat_ssl  
$ cd ~/.tomcat_ssl  
-
$ keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -alias tomcat -keystore .tomcatKeyStore  
+
$ keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -validity 360 -alias tomcat -keystore .tomcatKeyStore  
</source>
</source>
<code>'''.tomcatKeyStore'''</code> is the keysotre file name so change it to whatever you like.
<code>'''.tomcatKeyStore'''</code> is the keysotre file name so change it to whatever you like.
Line 344: Line 372:
e.g.)
e.g.)
----
----
-
  $ keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -alias tomcat -keystore .tomcatKeyStore  
+
  $ keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -validity 360 -alias tomcat -keystore .tomcatKeyStore  
  Enter keystore password: '''YOUR_KEYSTORE_PASSWORD'''
  Enter keystore password: '''YOUR_KEYSTORE_PASSWORD'''
  Re-enter new password: '''YOUR_KEYSTORE_PASSWORD'''
  Re-enter new password: '''YOUR_KEYSTORE_PASSWORD'''
Line 427: Line 455:
</source>
</source>
If the Eclipse workspace server.xml does not have it, added it. It is automatically added if the server is added to Eclipse workspace after server.xml modification happens (I am not sure if the same happens when the sever was added before modifying server.xml in the original tomcat).
If the Eclipse workspace server.xml does not have it, added it. It is automatically added if the server is added to Eclipse workspace after server.xml modification happens (I am not sure if the same happens when the sever was added before modifying server.xml in the original tomcat).
 +
 +
== Using Tomcat without Apache HTTP Server ==
 +
* Use [[Uncomplicated Firewall]]
 +
Open /etc/ufw/before.rules file and add the following lines to the top (after the first comment)
 +
# added by Kevin for Tomcat
 +
*nat
 +
:PREROUTING ACCEPT [0:0]
 +
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
 +
:PREROUTING ACCEPT [0:0]
 +
-A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443
 +
COMMIT

Latest revision as of 21:19, 10 May 2014

Contents

Apache Tomcat

Installation

-Download and extract the file

$ sudo tar -zxvf apache-tomcat-7.0.34.tar.gz 

-create user tomcat

$ sudo useradd -d /opt/tomcat_user_home tomcat -s /bin/bash 

# OR this would be better.
$ sudo adduser --disabled-login --gecos 'Tomcat' --home /opt/tomcat_user_home tomcat 
$ sudo passwd tomcat 

Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
$ chown -R tomcat:tomcat /opt/tomcat_user_home 
$ sudo chown -R tomcat:tomcat apache-tomcat-7.0.33 
$ sudo ln -s apache-tomcat-7.0.33/ tomcat 

-To run

$ su - tomcat 
Password: type tomcat password
$ cd /opt/tomcat/bin 
/opt/tomcat/bin$ ./catalina.sh start


-To automatically start when the computer is boot.

$ sudo ln -s /opt/tomcat/bin/catalina.sh /etc/init.d/tomcat 

-or it might be better to have a tomcat start and stop script with a proper $JAVA_HOME set. To do this create tomcat.sh file in the bin directory. (Make sure that there is no tomcat.sh in the bin directory).

$ cd /opt/tomcat/bin 
$ vim tomcat.sh 
#!/bin/sh

### BEGIN INIT INFO
# Provides:        tomcat
# Required-Start:  $network
# Required-Stop:   $network
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start/Stop Tomcat server
### END INIT INFO


# export JAVA_HOME=/usr/lib/jvm/java-6-sun
# export JAVA_HOME=/usr/lib/jvm/java-6-openjdk
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk
# export JAVA_OPTS="-server -Xms64m -Xmx192m -XX:MaxPermSize=256m -XX:+DisableExplicitGC -XX:-DoEscapeAnalysis"
export JAVA_OPTS="-server -Xms512m -Xmx768m -XX:MaxPermSize=384m -XX:+DisableExplicitGC -XX:-DoEscapeAnalysis"

PRG="$0"

while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

# Only set CATALINA_HOME if not already set
[ -z "$CATALINA_HOME" ] && CATALINA_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`

cd /opt/tomcat_user_home
/bin/su tomcat $CATALINA_HOME/bin/catalina.sh $1

  • If /dev/urandom should be used instead of /dev/random add -Djava.security.egd=file:/dev/./urandom to JAVA_OPTS.

e.g.)

export JAVA_OPTS="-server -Xms512m -Xmx768m -XX:MaxPermSize=384m -XX:+DisableExplicitGC -XX:-DoEscapeAnalysis -Djava.security.egd=file:/dev/./urandom"


-Make it executable (This script does not require tomcat user login to run the tomcat server. Instead, It will ask the tomcat user password when running the script).

$ chmod a+x tomcat.sh 

-put the symbolic link for the automatic start.

$ sudo ln -s /opt/tomcat/bin/tomcat.sh /etc/init.d/tomcat 
$ sudo chmod 755 /etc/init.d/tomcat 

Then to make it automatically start and stop when the server boots up and shuts down respectively.

sudo ln -s /etc/init.d/tomcat /etc/rc0.d/K10tomcat 
sudo ln -s /etc/init.d/tomcat /etc/rc1.d/K10tomcat 
sudo ln -s /etc/init.d/tomcat /etc/rc2.d/S90tomcat 
sudo ln -s /etc/init.d/tomcat /etc/rc3.d/S90tomcat 
sudo ln -s /etc/init.d/tomcat /etc/rc4.d/S90tomcat 
sudo ln -s /etc/init.d/tomcat /etc/rc5.d/S90tomcat 
sudo ln -s /etc/init.d/tomcat /etc/rc6.d/K10tomcat 

OR

$ cd /etc/init.d 
$ update-rc.d tomcat defaults 


References

http://linux-sxs.org/internet_serving/c140.html

http://www.linux.org/docs/ldp/howto/MMBase-Inst-HOWTO/x321.html

http://www.howtogeek.com/howto/linux/installing-tomcat-6-on-ubuntu/

http://www.jguru.com/faq/view.jsp?EID=425628

Configuration

Tomcat User Configuration

  • To create an encrypted password,
$ cd /tomcat/bin 
$ ./digest.sh -a SHA your_password 
your_password:564e340cd48437d2dfe876ee154cc99dc4d0d137


  • Add a tomcat manager login info to the /opt/tomcat/conf/tomcat-users.xml file.
$ vim /opt/tomcat/conf/tomcat-users.xml 
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager"/>
  <user username="managerid" password="564e340cd48437d2dfe876ee154cc99dc4d0d137" roles="manager"/>
</tomcat-users>
  • Add the following Realm element in the localhost Host element
<Realm className="org.apache.catalina.realm.MemoryRealm" digest="SHA" />
  • So it should be like this.
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
 
      <Realm className="org.apache.catalina.realm.MemoryRealm" digest="SHA" />
 
 
      ...
 
      </Host>
  • Restart the tomcat server.


Forward Request from Apache Web Server to Tomcat

Using mod_jk

Installation

$ sudo apt-get install libapache2-mod-jk 
  • Assumption: Apache web server is already installed.

-Reload config

$ sudo /etc/init.d/apache2 force-reload 

Configuration

-Check if mod_jk is enabled then edit /etc/apache2/mods-enabled/jk.load

LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so

JkWorkersFile /etc/apache2/workers.properties
JkLogFile /var/log/apache2/mod_jk.log
JkLogLevel debug
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "

JkMount /your_app worker1
JkMount /your_app/* worker1

-Create workers.properties file in the /etc/apache2/ directory.

workers.tomcat_home=/opt/tomcat
workers.java_home=/usr/lib/jvm/java-6-sun
ps=/
worker.list=worker1
worker.worker1.port=8009
worker.worker1.host=localhost
worker.worker1.type=ajp13
worker.worker1.lbfactor=1

-Restart Apache

$ sudo /etc/init.d/apache2 restart 

-Now run Tomcat and test it

go to 
http://localhost/your_app


  • If a virtual host should handle the request, set JkMount, JkUnMount and JkMountfile in the virtual host.
<VirtualHost *:80>
    ...

    JkMount /myapp worker1
    JkMount /myapp/* worker1
</VirtualHost>


References

http://ubuntuforums.org/showthread.php?t=219985

http://tomcat.apache.org/connectors-doc/index.html

http://tomcat.apache.org/connectors-doc/reference/uriworkermap.html

http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

http://tomcat.apache.org/connectors-doc/reference/apache.html

http://tomcat.apache.org/connectors-doc/reference/workers.html

http://swik.net/Tomcat+Apache?popular


Link Sub-domain Directly to Application

Using mod_jk

  • Open the workers.properties file in the /etc/apache2 directory.
  • Add another worker information.
workers.tomcat_home=/opt/tomcat
workers.java_home=/usr/lib/jvm/java-6-sun
ps=/
worker.list=worker1,worker2
worker.worker1.port=8009
worker.worker1.host=localhost
worker.worker1.type=ajp13
worker.worker1.lbfactor=1
worker.worker2.port=8009
worker.worker2.host=subdomain.yourdomain.com
worker.worker2.type=ajp13
worker.worker2.lbfactor=1
  • Set up JkMount in the apache virtual host configuration.
<VirtualHost *:80>
    ServerAdmin master@yourdomain.com

    ServerName subdomain.yourdomain.com

    JkMount / worker2
    JkMount /* worker2

</VirtualHost>
  • Open the $CATALINA_HOME/conf/server.xml file to set up a tomcat virtual host.
  • Add a new virtual host info inside the Engine element.
    <Engine name="Catalina" defaultHost="localhost">
      ... Default Host Info ...
 
      <Host name="subdomain.yourdomain.com" appBase="/opt/some_path/webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
          <!-- if necessary
          <Context path="" docBase="application_path" debug="0" reloadable="true" />
          -->
      </Host>
    </Engine>
  • OPTIONAL: If the context information which is, in the example, the part commented out is set, the application_path must exist in the appBase directory which is ,in this example, /opt/some_path/webapps directory.
/opt/some_path/webapps/application_path
  • Restart Tomcat and Apache.
$ /etc/init.d/tomcat stop 
$ /etc/init.d/tomcat start 
$ /etc/init.d/apache restart 


Realm Configuration

    <Resource name="jdbc/eVideoDataSource" auth="Container" type="javax.sql.DataSource"
     maxActive="2" maxIdle="1" maxWait="180"
     username="userId" password="password" driverClassName="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost:3306/db_name?autoReconnect=true"/>
 
 
    <Realm className="org.apache.catalina.realm.DataSourceRealm" debug="99" 
	dataSourceName="jdbc/eVideoDataSource" localDataSource="true"
	userTable="login" userNameCol="username" userCredCol="password" digest="SHA-1" 
	userRoleTable="user_roles" roleNameCol="role_name" allRolesMode="strict" />

allRolesMode attribute can be one of "strict" or "authOnly" or "strictAuthOnly". If there is no allRolesMode specified, it will be "strict" by default.


-The following is the part of RealmBase class source code from the Apache Tomcat server 5.5.25.

        /**
         * Use the strict servlet spec interpretation which requires that the user
         * have one of the web-app/security-role/role-name 
         */
        public static final AllRolesMode STRICT_MODE = new AllRolesMode("strict");
        /**
         * Allow any authenticated user
         */
        public static final AllRolesMode AUTH_ONLY_MODE = new AllRolesMode("authOnly");
        /**
         * Allow any authenticated user only if there are no web-app/security-roles
         */
        public static final AllRolesMode STRICT_AUTH_ONLY_MODE = new AllRolesMode("strictAuthOnly");

SSL

KeyStore

Create a folder to store the keystore file.

$ mkdir ~/.tomcat_ssl

Create a keystore file using Java's keytool

$ cd ~/.tomcat_ssl 
$ keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -validity 360 -alias tomcat -keystore .tomcatKeyStore

.tomcatKeyStore is the keysotre file name so change it to whatever you like.

e.g.)


$ keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -validity 360 -alias tomcat -keystore .tomcatKeyStore 
Enter keystore password: YOUR_KEYSTORE_PASSWORD
Re-enter new password: YOUR_KEYSTORE_PASSWORD
What is your first and last name?
  [Unknown]:  localhost (e.g. your.domain.com)
What is the name of your organizational unit?
  [Unknown]:  Blahblah Development Team
What is the name of your organization?
  [Unknown]:  Your Company Name
What is the name of your City or Locality?
  [Unknown]:  Sydney
What is the name of your State or Province?
  [Unknown]:  New South Wales
What is the two-letter country code for this unit?
  [Unknown]:  AU
Is CN=localhost, OU=BlahBlah Development Team, O=Your Company Name, L=Sydney, ST=New South Wales, C=AU correct?
  [no]:  yes

Enter key password for <tomcat>
  (RETURN if same as keystore password): PRESS_ENTER

Tomcat Configuration

Go to the directory where the Tomcat is located.

Open the server.xml file to edit.

$TOMCAT_HOME/conf/server.xml

Add the following lines

    <Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
               disableUploadTimeout="true" enableLookups="true"
               keystoreFile="/path/to/keystore"
               keystorePass="YOUR_KEYSTORE_PASSWORD"
               maxSpareThreads="75" maxThreads="200" minSpareThreads="5" 
               port="8443" scheme="https" secure="true" sslProtocol="TLS"/>

After

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />

So it may look like

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
 
    <!-- Added for SSL -->
    <Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
               disableUploadTimeout="true" enableLookups="true"
               keystoreFile="${user.home}/.tomcat_ssl/.tomcatKeyStore"
               keystorePass="YOUR_KEYSTORE_PASSWORD"
               maxSpareThreads="75" maxThreads="200" minSpareThreads="5" 
               port="8443" scheme="https" secure="true" sslProtocol="TLS"/>

Open server.xml in Eclipse workspace to see if it is set correctly.

Server
  +Tomcat v6.0 Server at localhost-config
    +server.xml

If the Eclipse workspace server.xml does not have it, added it. It is automatically added if the server is added to Eclipse workspace after server.xml modification happens (I am not sure if the same happens when the sever was added before modifying server.xml in the original tomcat).

Using Tomcat without Apache HTTP Server

* Use Uncomplicated Firewall

Open /etc/ufw/before.rules file and add the following lines to the top (after the first comment)

# added by Kevin for Tomcat
*nat
:PREROUTING ACCEPT [0:0]
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
:PREROUTING ACCEPT [0:0]
-A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443
COMMIT
Personal tools