ubuntu 14.04 apache2 tomcat7 jk_mod java web

葛威
2023-12-01

先讲下环境

ubuntu:

sudo lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 14.04.5 LTS
Release:	14.04
Codename:	trusty
java:
java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
apache版本:
/usr/share/tomcat7/bin$ apachectl -v
Server version: Apache/2.4.7 (Ubuntu)
Server built:   May  9 2017 16:14:10
tomcat版本:
/usr/share/tomcat7/bin$ ./version.sh
Using CATALINA_BASE:   /usr/share/tomcat7/webapps
Using CATALINA_HOME:   /usr/share/tomcat7
Using CATALINA_TMPDIR: /usr/share/tomcat7/webapps/temp
Using JRE_HOME:        /usr/lib/jvm/java-8-sun/jre
Using CLASSPATH:       /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.52 (Ubuntu)
Server built:   Apr 5 2017 06:27:12
Server number:  7.0.52.0
OS Name:        Linux
OS Version:     3.13.0-105-generic
Architecture:   amd64
JVM Version:    1.8.0_131-b11
JVM Vendor:     Oracle Corporation
以上这些部件,与将来要用的开发环境是有很大的关联的,所以请谨慎选择版本
第一步 安装java

我安装的是oracle java 1.8,先到oracle的网站上下载64位版本的jdk,然后安装。注意的是,如果你是在本地下载,然后远程通过scp复制tar压缩文件到服务器上时,解压的时候请使用 tar -xf ,也就是说去掉Z参数,因为用的ascii传输,否则记得用二进制传输。安装请参照文章:http://blog.csdn.net/hejisan/article/details/8487568

我的安装在位置:/usr/lib/jvm/java-8-sun,这也是我的JAVA_HOME的位置,安装完以后就是设置环境变量。对于Ubuntu设置环境变量,有两个文件,一个是/etc/profile,二一个是~/.bashrc,到这两个地方设置你的对应的环境变量。然后用source命令重新加载环境变量。之后最好试用java -version命令看看java命令是不是能正常工作及版本是不是正确的。

补上我的环境变量设置:

export JAVA_HOME=/usr/lib/jvm/java-8-sun
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH

第二步 安装apache2 及 jk_mod

安装倒是很简单:sudo apt-get install apache2 ,一切都是自动的,对于Ubuntu而言。

然后安装jk_mod :sudo apt-get install libapache2-mod-jk ,一切也是自动的

第三步 安装tomcat7

安装命令:sudo apt-get install tomcat7

安装完后,有两个重要的事情必须要做:

1、设置tomcat7运行环境:

请在~/.bashrc及/etc/profile中设置:

export CATALINA_HOME=/usr/share/tomcat7
export CATALINA_BASE=/usr/share/tomcat7/webapps 
然后重新source导入文件

2、设置tomcat中的java环境变量

由于某些原因,tomcat在启动的时候不能正常的读取环境变量中的java设置,要到/usr/share/tomcat7/bin路径下,编辑文件setclasspath.sh ,因为这个文件会在startup.sh文件运行的时候引用运行,而这个文件中获取或者设置了环境变量,添加如下行:

# -----------------------------------------------------------------------------
#  Set JAVA_HOME or JRE_HOME if not already set, ensure any provided settings
#  are valid and consistent with the selected start-up options and set up the
#  endorsed directory.
# -----------------------------------------------------------------------------

# Make sure prerequisite environment variables are set
JAVA_HOME=/usr/lib/jvm/java-8-sun
JRE_HOME=/usr/lib/jvm/java-8-sun/jre
否则你的任何java程序都不能在tomcat7中运行,你懂的。

下面要高潮了,其中不同的版本,要踏过多少坑才能成功,光看这篇文章是无法理解到的

第四步  设置apache及jk_mod

1、设置apache第一个网站

先设一个站点,应用于测试

以下是全局设置,与网上谣传的诸多资料不符的是,事实上,

Apache/2.4.7 (Ubuntu)
这个版本的默认配置文件并不叫什么httpd.conf,也不叫其它,而是在:

/etc/apache2/apache2.conf

一定要谨记!我先列一下我的文件,而讲下这里面的注意事项:

# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#	/etc/apache2/
#	|-- apache2.conf
#	|	`--  ports.conf
#	|-- mods-enabled
#	|	|-- *.load
#	|	`-- *.conf
#	|-- conf-enabled
#	|	`-- *.conf
# 	`-- sites-enabled
#	 	`-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.


# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
Mutex file:${APACHE_LOCK_DIR} default

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5


# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf


# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.

<Directory /var/www/>
	Options Indexes FollowSymLinks
	AllowOverride None
	Require all granted
</Directory>

#<Directory /srv/>
#	Options Indexes FollowSymLinks
#	AllowOverride None
#	Require all granted
#</Directory>




# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
	Require all denied
</FilesMatch>


#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
ServerName localhost:80
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
注意的是,与默认的文件相比,增加了一行ServerName localhost:80,不然会报类似如下:

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

的错误。

全局设置之后,再来修改默认网站。进入目录:/etc/apache2/sites-enabled,看到有一个000-default.conf的文件,没错, 就是它,我的修改后内容如下:

<VirtualHost *:80>
	# The ServerName directive sets the request scheme, hostname and port that
	# the server uses to identify itself. This is used when creating
	# redirection URLs. In the context of virtual hosts, the ServerName
	# specifies what hostname must appear in the request's Host: header to
	# match this virtual host. For the default virtual host (this file) this
	# value is not decisive as it is used as a last resort host regardless.
	# However, you must set it for any further virtual host explicitly.

	#ServerName www.example.com
	ServerName test.test.top
	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html

	# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
	# error, crit, alert, emerg.
	# It is also possible to configure the loglevel for particular
	# modules, e.g.
	#LogLevel info ssl:warn
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
JkMount /* DLOG4J
JkUnMount /*.jpg *
JkUnMount /*.html *
	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined

	# For most configuration files from conf-available/, which are
	# enabled or disabled at a global level, it is possible to
	# include a line for only one particular virtual host. For example the
	# following line enables the CGI configuration for this host only
	# after it has been globally disabled with "a2disconf".
	#Include conf-available/serve-cgi-bin.conf
</VirtualHost>
其中,
ServerName test.test.top

这一行是我自己添加的,这是我的域名,这个虚拟主机站点的名称

另外,顺便把重点提一下

JkMount /* DLOG4J
JkUnMount /*.jpg *
JkUnMount /*.html *

这是jk_mod的配置示例,一定要在这里配置,不然就踏坑了!!!!大概的意思就是,首先决定把所有对test.test.top站的访问都交给 DLOG4J这个东西来处理,但是,对于表态的诸如:jpg图像文件、html表态页面这样的东西,就必转交给tomcat来处理了,这正是这篇文章及这种架构的主要目的。后面会接着讲。

下面开始设置jk mod,这个东西是当前apache连接tomcat的比较稳定、经典的方式之一。其中现在主要的连接方式主要有三种:jk_mod、http_proxy和ajp_proxy。(请参阅:https://www.ibm.com/developerworks/cn/opensource/os-lo-apache-tomcat/,但是不要使用其中的配置方式,有坑!)正面开始讲设置:

进入目录:/etc/apache2/mods-enabled,安装jk后,会在此目录看到一个jk.conf及jk.load的文件,我们只要编辑jk.conf,先粘我的内容:

<IfModule jk_module>

    # We need a workers file exactly once
    # and in the global server

#    JkWorkersFile /etc/libapache2-mod-jk/workers.properties
    JkWorkersFile /etc/apache2/workers.properties
JkMountFile /etc/apache2/uriworkermap.properties
    # Our JK error log
    # You can (and should) use rotatelogs here
    JkLogFile /var/log/apache2/mod_jk.log

    # Our JK log level (trace,debug,info,warn,error)
    JkLogLevel info

    # Our JK shared memory file
    JkShmFile /var/log/apache2/jk-runtime-status

    # Define a new log format you can use in any CustomLog in order
    # to add mod_jk specific information to your access log.
    # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{Cookie}i\" \"%{Set-Cookie}o\" %{pid}P %{tid}P %{JK_LB_FIRST_NAME}n %{JK_LB_LAST_NAME}n ACC %{JK_LB_LAST_ACCESSED}n ERR %{JK_LB_LAST_ERRORS}n BSY %{JK_LB_LAST_BUSY}n %{JK_LB_LAST_STATE}n %D" extended_jk

    # This option will reject all requests, which contain an
    # encoded percent sign (%25) or backslash (%5C) in the URL
    # If you are sure, that your webapp doesn't use such
    # URLs, enable the option to prevent double encoding attacks.
    # Since: 1.2.24
    # JkOptions +RejectUnsafeURI

    # After setting JkStripSession to "On", mod_jk will
    # strip all ";jsessionid=..." from request URLs it
    # does *not* forward to a backend.
    # This is useful, if all links in a webapp use
    # URLencoded session IDs and parts of the static
    # content should be delivered directly by Apache.
    # Of course you can also do it with mod_rewrite.
    # Since: 1.2.21
    # JkStripSession On

    # Start a separate thread for internal tasks like
    # idle connection probing, connection pool resizing
    # and load value decay.
    # Run these tasks every JkWatchdogInterval seconds.
    # Since: 1.2.27
    JkWatchdogInterval 60

    # Configure access to jk-status and jk-manager
    # If you want to make this available in a virtual host,
    # either move this block into the virtual host
    # or copy it logically there by including "JkMountCopy On"
    # in the virtual host.
    # Add an appropriate authentication method here!
    <Location /jk-status>
        # Inside Location we can omit the URL in JkMount
        JkMount jk-status
        Order deny,allow
        Deny from all
        Allow from all
    </Location>
    <Location /jk-manager>
        # Inside Location we can omit the URL in JkMount
        JkMount jk-manager
        Order deny,allow
        Deny from all
        Allow from all
    </Location>

    # If you want to put all mounts into an external file
    # that gets reloaded automatically after changes
    # (with a default latency of 1 minute),
    # you can define the name of the file here.
    # JkMountFile conf/extra/uriworkermap.properties

    # Example for Mounting a context to the worker "balancer"
    # The URL syntax "a|b" instantiates two mounts at once,
    # the first one is "a", the second one is "ab".
    # JkMount /myapp|/* balancer

    # Example for UnMounting requests for all workers
    # using a simple URL pattern
    # Since: 1.2.26
    # JkUnMount /myapp/static/* *

    # Example for UnMounting requests for a named worker
    # JkUnMount /myapp/images/* balancer

    # Example for UnMounting requests using regexps
    # SetEnvIf REQUEST_URI "\.(htm|html|css|gif|jpg|js)$" no-jk

    # Example for setting a reply timeout depending on the request URL
    # Since: 1.2.27
    # SetEnvIf Request_URI "/transactions/" JK_REPLY_TIMEOUT=600000

    # Example for disabling reply timeouts for certain request URLs
    # Since: 1.2.27
    # SetEnvIf Request_URI "/reports/" JK_REPLY_TIMEOUT=0

    # IMPORTANT: Mounts and virtual hosts
    # If you are using VirtualHost elements, you
    # - can put mounts only used in some virtual host into its VirtualHost element 
    # - can copy all global mounts to it using "JkMountCopy On" inside the VirtualHost
    # - can copy all global mounts to all virtual hosts by putting
    #   "JkMountCopy All" into the global server
    # Since: 1.2.26

</IfModule>

注意的是,要添加

JkWorkersFile /etc/apache2/workers.properties
JkMountFile /etc/apache2/uriworkermap.properties(后经证实,这个应该是没有用的)
这几行
<Location /jk-status>
        # Inside Location we can omit the URL in JkMount
        JkMount jk-status
        Order deny,allow
        Deny from all
        Allow from all
    </Location>
    <Location /jk-manager>
        # Inside Location we can omit the URL in JkMount
        JkMount jk-manager
        Order deny,allow
        Deny from all
        Allow from all
    </Location>

这个我忘记是不是我添加的了,反正加一下吧。再粘出 /etc/apache2/workers.properties 这个文件:

worker.list=DLOG4J,status
worker.s1.port=8888
worker.s1.host=test.test.top
worker.s1.type=ajp13
worker.DLOG4J.type=lb
worker.DLOG4J.balance_workers=s1
worker.status.type=status
worker.list=jk-status
worker.jk-status.type=status
worker.jk-status.read_only=true
worker.list=jk-manager
worker.jk-manager.type=status

这个文件的大概意思是讲使用一个叫s1的服务端口为8888的tomcat worker来做相关工作,使用ajp13协议栈连接,其它东西可看可不看。还有一个叫 /etc/apache2/uriworkermap.properties 的文件,这个文件貌似没有起到真正的作用,我还是先粘出来:

/*=DLOG4J
/jkstatus=status
/jk-status=jk-status
/jk-manager=jk-manager
!/*.gif=DLOG4J
!/*.png=DLOG4J
!/*.css=DLOG4J
!/*.js=DLOG4J
!/*.htm=DLOG4J
!/*.html=DLOG4J
!/*.jpg=DLOG4J


特别是这个不进入DLOG4J的,好像不起作用,后面我再琢磨下写到评论里。
至此,apache及jk的配置就差不多了,暂时还不能重启,因为tomcat还没有配置好。


第五步 设置tomcat7

自从设置好

export CATALINA_HOME=/usr/share/tomcat7
export CATALINA_BASE=/usr/share/tomcat7/webapps 
这两个环境变量后,tomcat后面的设置就变得简单了,因为启动的位置都指定了,那么我们就来到这个CATALINA_HOME位置:
cd /usr/share/tomcat7
大概看一下这个目录
然后,最主要的就是一个文件/usr/share/tomcat7/conf/server.xml,当然,如果不存在这个文件,你要用命令复制一个样本过来,不然的话从头开始写可没那么容易:
sudo cp /etc/tomcat7/server.xml /usr/share/tomcat7/conf/server.xml
然后,我粘我的示例:
<?xml version='1.0' encoding='utf-8'?>

<Server port="8005" shutdown="SHUTDOWN">
  <!-- 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="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               URIEncoding="UTF-8"
               redirectPort="8443" /> 
-->
    <!-- A "Connector" using the shared thread pool-->
    <Connector executor="tomcatThreadPool"
               port="8888" protocol="AJP/1.3"
               connectionTimeout="20000"
		maxHttpHeaderSize="8192"
               redirectPort="8443"
		useSendfile="false" />
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector port="8009" 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="test.belink.top" jvmRoute="s1">

      <!--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="test.belink.top"  appBase="webapps" deployOnStartup="true" 
            unpackWARs="true" autoDeploy="false">
<Context docBase="/usr/share/tomcat7/webapps/a.war" path="" />
        <!-- 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 "%r" %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

讲一下如下几个地方:

<Connector executor="tomcatThreadPool"
               port="8888" protocol="AJP/1.3"
               connectionTimeout="20000"
                maxHttpHeaderSize="8192"
               redirectPort="8443"
                useSendfile="false" />

executor是我自己加的,参照其它地方。port="8888",旨在指定对外服务端口,protocol="AJP/1.3",这里的话,是从protocol="HTTP/1.1"这个改过来的,jk连接tomcat用的就是这个协议,而不是http协议,不是我们正常访问的逻辑,所以这个tomcat站点也是不通过浏览器访问的,而只能通过apache jk来代理连接访问。然后maxHttpHeaderSize="8192"及useSendfile="false"是我自己加的,不然会报解析请求头错误的。再接着往下看:

<Engine name="Catalina" defaultHost="test.test.top" jvmRoute="s1">

defaultHost="test.test.top"这个是我自己加的,只接受这个域名解析,jvmRoute,对外的服务路径,与前面jk 配置里的一致,这是重点,一定要的!!!再接着往下看:

<Host name="test.test.top"  appBase="webapps" deployOnStartup="true"  unpackWARs="true" autoDeploy="false">
      <Context docBase="/usr/share/tomcat7/webapps/a.war" path="" />     
      <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />
  </Host>

这个涉及到tomcat比较细致的配置了,大概意思是讲,配置一个这样的tomcat站点,主机名是test.test.top,站点应用的base目录为$CATALINA_HOME/webapps,启动站点就部署,自动解压war,war有更新不自动部署,war存放的位置在/usr/share/tomcat7/webapps/a.war,path="",代表访问路径即为网站根目录,其它参数不述了。顺便粘一个我的测试网站的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>web01_exec</display-name>
    <welcome-file-list>
        <welcome-file>home</welcome-file>
    </welcome-file-list>
  <servlet>
      <servlet-name>dateServlet</servlet-name>
      <servlet-class>web.DateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>dateServlet</servlet-name>
      <url-pattern>/home</url-pattern>
  </servlet-mapping>
  
  <servlet>
		<servlet-name>ForwardServlet</servlet-name>
		<servlet-class>web.Servlet2Jsp</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ForwardServlet</servlet-name>
		<url-pattern>/forward</url-pattern>
	</servlet-mapping>
  
      <!-- LOG4J-->  
      <display-name>Log4jWebDemo1</display-name>
     
    <context-param>
        <param-name>log4j-config-location</param-name>
        <param-value>WEB-INF/classes/log4j.properties</param-value>
    </context-param>
      
     <context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>webApp.root</param-value>
	</context-param>
    <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 -->  
    <context-param>    
         <param-name>log4jRefreshInterval</param-name>    
         <param-value>3000</param-value>    
    </context-param>   
   <listener>
		<listener-class>net.codejava.servlet.ContextListener</listener-class>
	</listener>
   
  <!-- LOG4J-->  
  <!-- For security reasons, using the manager webapp is restricted to users with role "manager-gui". 
  The host-manager webapp is restricted to users with role "admin-gui". 
  Users are defined in /etc/tomcat7/tomcat-users.xml.
  --> 
  
</web-app>

设置基本上就完成了,下面写一些关于测试与维护的事情

先把站点war放到对应位置

启动顺序:
先启动tomcat7:
/usr/share/tomcat7/bin$ sudo ./startup.sh
再重启apache
sudo service apache2 restart

ubuntu 下tomcat7启动慢
在bin/catalina.sh中加入这么一行:
#!/bin/sh
export CATALINA_OPTS="-Djava.security.egd=file:/dev/./urandom"


scp ./Desktop/ssm.war ubuntu@ybh.belink.top:/home/ubuntu


ssh ubuntu@ybh.belink.top

sudo ./apache-tomcat-7.0.73/bin/catalina.sh stop

sudo rm -r ./apache-tomcat-7.0.73/webapps/ssm.war


sudo rm -r ./apache-tomcat-7.0.73/webapps/ssm

sudo rm -r ./apache-tomcat-7.0.73/webapps/ROOT

sudo rm -r ./apache-tomcat-7.0.73/work/Catalina/ybh.belink.top/

cp ssm.war ./apache-tomcat-7.0.73/webapps/

sudo ./apache-tomcat-7.0.73/bin/startup.sh -Dfile.encoding=UTF-8

tail -f apache-tomcat-7.0.73/logs/catalina.out


日志位置:


apache2的日志位置:

/var/log/apache2
大概有这些:


access.log  error.log  jk-runtime-status.17610  jk-runtime-status.17610.lock  mod_jk.log  other_vhosts_access.log
tomcat7的日志位置:


/usr/share/tomcat7/logs
大概有这些:
catalina.out                         localhost_access_log.2017-05-29.txt  localhost_access_log.2017-05-31.txt  logs
localhost_access_log.2017-05-28.txt  localhost_access_log.2017-05-30.txt  localhost_access_log.2017-06-01.txt


常见问题及解决:
linux系统tomcat重启老是端口被占用 
使用lsof -i :80|grep -v "PID"|awk '{print "kill -9",$2}'命令后所有80端口进程删除。重新启动tomcat,系统正常运行。
http://cmm.iteye.com/blog/654327
分析:netstat -an查看到大量的80端口进程僵死,重启tomcat.tomcat启动失败,网页依然无法打开.
停止tomcat进程shutdown.sh,停止tomcat后telnet 127.0.0.1 80,发现80端口依然可用。netstat -an|grep 80 查看发现有许多80端口进程在里面,使用kill pid命令终止进程,无用。使用lsof -i :80|grep -v "PID"|awk '{print "kill -9",$2}'命令后所有80端口进程删除。重新启动tomcat,系统正常运行。不过为什么tomcat在关闭时却不能将80端口的进程一并关闭的原因需要分析一下。
还有一个jk_mod的配置文件位置:/etc/libapache2-mod-jk/

常用命令:
1、lsof
查看所有进程的文件打开数
lsof |wc -l
查看某个进程打开的文件数
lsof -p pid |wc -l
查看某个文件被打开的次数
lsof |grep 文件名|wc -l (我用这个命令证实了代码中没有被close的文件一直在增加)

2、使用netstat 命令查看占用情况
netstat -ap |grep 8080 //查找tomcat端口是否被占用
3、其他
netstat -tln //表示以数字形式查看正在监听的端口
netstat -ap //查看所有应用占用端口情况


参考文章:
https://www.ibm.com/developerworks/cn/opensource/os-lo-apache-tomcat/
http://blog.csdn.net/hejisan/article/details/8487568
http://www.oschina.net/question/2438081_2148242?sort=time
http://blog.csdn.net/hejisan/article/details/66473354
http://myhat.blog.51cto.com/391263/785131/
http://ask.csdn.net/questions/162513



The description below uses the variable name $CATALINA_HOME to refer to the directory into which you have installed Tomcat 5, and is the base directory against which most relative paths are resolved. However, if you have configured Tomcat 5 for multiple instances by setting a CATALINA_BASE directory, you should use $CATALINA_BASE instead of $CATALINA_HOME for each of these references.

从这段描述可以看出CATALINA_HOME和CATALINA_BASE的区别。简单的说,CATALINA_HOME是Tomcat的安装目 录,CATALINA_BASE是Tomcat的工作目录。如果我们想要运行Tomcat的 多个实例,但是不想安装多个Tomcat软件副本。那么我们可以配置多个工作 目录,每个运行实例独占一个工作目录,但是共享同一个安装目录。

 


 

Tomcat每个运行实例需要使用自己的conf、logs、temp、webapps、work和shared目录,因此CATALINA_BASE就 指向这些目录。 而其他目录主要包括了Tomcat的二进制文件和脚本,CATALINA_HOME就指向这些目录。

如果我们希望再运行另一个To
mcat实例,那么我们可以建立一个目录,把conf、logs、temp、webapps、work和shared拷贝 到该目录下,然后让CATALINA_BASE指向该目录即可。

 

在一台服务器上,可以运行多个tomcat实例,不需要安装多个tomcat,可以采用不同的用户,以test用户为例,拷贝/usr/local/apache-tomcat-6.0.18目录到/home/test下,删除/home/test/apache-tomcat-6.0.18/bin子目录(此目录不需要),编辑/home/test/.bash_profile文件,设置CATALINA_HOME指向刚才的安装目录/usr/local/apache-tomcat-6.0.18,设置JAVA_HOME指向刚才的安装目录/usr/java/jdk1.6.0_11。设置CATALINA_BASE指向/home/test/apache-tomcat-6.0.18,设置CATALINA_OPTS跟/root/.bash_profile的一致(jmx管理端口用不同的端口号)











 类似资料:

相关阅读

相关文章

相关问答