# Tomcat 多实例部署 教程

Tomcat 多实例部署 教程

我们首先看到的是tomcat的目录结构,其每个文件夹有以下用途:

bin – 包含所有运行tomcat的二进制和脚本文件
lib – 包含tomcat使用的所有共享库
conf - 包含配置信息,如tomcat绑定的端口等
logs – 包含所有的日志文件
temp – 此目录是tomcat存放的临时文件
webapps – 此目录非常重要,这里存放所有的应用程序war包
work – 如果应用程序包含jsp文件,那么每个jsp文件会被编译转化为servlet,存放于此

当我们运行Tomcat时,会用到5个环境变量。他们是:

CATALINA_HOME
CATALINA_BASE
CATALINA_TMPDIR
JRE_HOME/JAVA_HOME
CLASSPATH
在以上列表中,CATALINA_HOME和JAVA_HOME是必要的环境变量。其它的都可以通过CATALINA_HOME来转换,是可选的。

CATALINA_HOME – 此环境变量是tomcat安装/提取的根目录。所以通过CATALINA_HOME,可以得到bin和lib目录。

CATALINA_BASE – 如果不指定则是CATALINA_HOME的值。该变量指向的目录里面包括每个运行实例需要使用自己的conf、logs、temp、webapps、work目录

CATALINA_BASE (Optional) Base directory for resolving dynamic portions
of a Catalina installation. If not present, resolves to
the same directory that CATALINA_HOME points to.
这个就是用来解决多实例的一个配置, CATALINA_BASE 配置项 所指定的目录,需要一个 conf 目录,而conf就包含了配置端口和项目路径。而默认的CATALINA_BASE 指向了Tomcat的根目录。可能还不怎么清楚,要怎么配置多CATALINA_BASE
了解tomcat的主配置文件(server.xml)结构及含义
如下图所示这里写图片描述,前端请求被tomcat直接接收或者由前端的代理,通过HTTP,或者AJP代理给Tomcat,此时请求被tomcat中的connector接收,不同的connector和Engine被service组件关联起来,在一个Engine中定义了许多的虚拟主机,由Host容器定义,每一个Host容器代表一个主机,在各自的Host中,又可以定义多个Context,用此来定义一个虚拟主机中的多个独立的应用程序。

因此要运行多少实例方法 可以在host 配置多个context ,这种方法要重启tomcat 所有应用会重新启动 非常麻烦!
下面方法具体步骤:

1解压 tomcat安装在/usr/local/tomcat 上

tomcat安装目录

2在tomcat根目录上创建文件夹default_template,复制tomcat conf,logs 文件到default_template 文件内,

default_template 包括如下内容:

conf
复制原来tomcat原来的所有文件,并修改其中server.xml 文件,具体内容如下:
<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="server_port" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- 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="http_port" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the BIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="ajp_port" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>
logs
复制原来logs 目录即可
tomcat.sh
代码如下
#!/bin/sh
# 本脚本参考:http://www.ttlsa.com
 . /etc/init.d/functions
 RETVAL=$?
# tomcat实例目录,重要,这个就是指向了含有 conf的实例目录,这个比较重要!在于 export 会将指定的变量临时加入用户变量
# export CATALINA_BASE="$PWD"
export CATALINA_BASE="catalina_base_dir"
# tomcat安装目录,这个指向tomact所在的路径
export CATALINA_HOME="catalina_home_dir"
#下面就是用来启动了
case "$1" in
start)
if [ -f $CATALINA_HOME/bin/startup.sh ];then
echo $"Start Tomcat"
$CATALINA_HOME/bin/startup.sh
fi
;;
stop)
if [ -f $CATALINA_HOME/bin/shutdown.sh ];then
$CATALINA_HOME/bin/shutdown.sh
fi
;;
*)
echo $"Usage: $0 {start|stop}"
exit 1
;;
esac
exit $RETVAL

3多实例文件夹在 创建两个目录/data/website 和/data/webapps

/data/website/
存放生产配置文件的脚步文件:其中脚步代码

#/bin/sh
httpport=""
serverport=""
ajpport=""
#这里定义webapps的目录,根据域名在此生成对应的目录
webappsdir="/data/webapps"
#这里定为配置文件的目录,根据域名生成对应的配置文件
websitedir="/data/website"
#域名
domain=""
#Tomcat的Home目录
tomcathome="/usr/local/tomcat"
#上面的配置文件目录
templatedir="/usr/local/tomcat/default_template"
#访问路径,默认就是根目录,现在没用到
accesspath=""
#配置后是否直接运行
isrun="n"

echo "===========Input Port========="
#输入运行的端口号,每个实例都需要不同的端口号,我是以8181为基础,8182,8183 这样递增
read -p "(http run port):" httpport

if [ "$httpport" = "" ]; then
     echo "http port can't be empty"
     exit
fi
#server port 如果为空,则默认在上面的哪个端口中加个3,如:38181,38182
read -p "(server port default 3$httpport):" serverport
if [ "$serverport" = "" ]; then
    serverport=3$httpport
fi
#ajport 和server port一样,运行端口千米加个4。如:48181
read -p "(ajp port default 4$httpport):" ajpport
if [ "$ajpport" = "" ]; then
    ajpport=4$httpport
fi
#域名
echo "============input domain============="
#read -p "domain:" domain
read -p "domain:" domain
if [ "$domain" = "" ]; then
    echo " domain can't be empty"
    exit
fi

if [ -d "$websitedir/$domain" ]; then
        echo "==========================="
        echo "$domain is exist!"
        echo "==========================="      
    exit
fi

#如果不想用默认的webapps目录,则自定义输入,否则使用默认的+域名
echo "============input webapps dir==========="
webappsdir_input=""
read -p "webapps dir:(default $webappsdir/$domain):" webappsdir_input
if [ "$webappsdir_input" = "" ]; then
    webappsdir_input=$webappsdir/$domain
fi
#配置完后是否直接运行
echo "=========is run now?(y/n)======="
read -p "(default n):" isrun



if [ ! -d "$webappsdir_input" ]; then
    mkdir -p $webappsdir_input
fi

echo "http port:$httpport"
echo "server port:$serverport"
echo "ajp port:$ajpport"
echo "domain :$domain"
echo "webapps dir :$webappsdir_input"
echo "======== Cp ========"
cp $templatedir $websitedir/$domain -r
#以下均为替换 占位符
echo "=========replace======="
#sed -i "s/catalina_base_dir/catalina_base_dir_r/g" `grep catalina_base_dir -rl ./tomcat.sh`
echo $webappsdir_input
echo "=======replacee tomcat======"

#tomcat.sh
sed -i "s#catalina_base_dir#${websitedir}/${domain}#g" `grep catalina_base_dir -rl $websitedir/$domain/tomcat.sh`
sed -i "s#catalina_home_dir#${tomcathome}#g" `grep catalina_home_dir -rl $websitedir/$domain/tomcat.sh`
echo "-----------replacee -servel----------------"

#conf/server.xml
sed -i "s#server_port#${serverport}#g" `grep server_port -rl $websitedir/$domain/conf/server.xml`
sed -i "s#http_port#${httpport}#g" `grep http_port -rl $websitedir/$domain/conf/server.xml`
sed -i "s#ajp_port#${ajpport}#g" `grep ajp_port -rl $websitedir/$domain/conf/server.xml`
sed -i "s#localhost_webapps#${tomcathome}/webapps#g" `grep localhost_webapps -rl $websitedir/$domain/conf/server.xml`
echo "----------replacee -rootl------------"

#ROOT.xml
sed -i "s#webapps_dir#${webappsdir_input}#g" `grep webapps_dir -rl $websitedir/$domain/conf/Catalina/localhost/ROOT.xml`

#生成默认的index.html
if [ ! -f "$webappsdir_input/index.html" ]; then
    touch "$webappsdir_input/index.html"
    echo "<html><head><title>$domain</title></head><body>$domain</body><html>" > $webappsdir_input/index.html
fi


if [ "$isrun" = "y" ]; then
    sh $websitedir/$domain/tomcat.sh start
fi

#OK 
echo "=========Success============="

/data/webapps/

该目录主要要部署的文件war包

4 运行脚本文件multomcat.sh 根据提示输入端口号,域名等 其中脚本会根据域名在上面两个目录文件夹创建域名文件夹,并拷贝/usr/local/tomcat/default_template 文件内容

5 运运行域名下的tomcat.sh文件

运行过程如图所示
这里写图片描述

附件下载
参考1Tomcat 多实例部署脚本

参考2简书的文章

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页