使用Nginx反向代理tomcat服務器

大綱

一、Tomcat
基本配置

1.爲Tomcat提供SysV腳本
2.catalina 腳本講解
3.telnet 登錄管理Tomcat
4.配置Tomcat虛擬主機
5.Tomcat圖形管理接口

6.部署JSP網站案例


二、Nginx反向代理Tomcat服務



1.Nginx將請求反向代理到後端Tomcat
2.Nginx將圖片緩存到本地
3.Nginx將請求實現動靜分離


注,實驗環境說明,操作系統:CentOS 6.4x86_64,軟件版本:jdk-7u40、apache-tomcat-7.0.42、Nginx-1.4.2,博客中所用到的軟件請到這裏下載:http://yunpan.cn/QGBCLwrZnpLMS。

一、Tomcat 基本配置

1.爲Tomcat提供SysV腳本

注,在上一篇博文中我們已經演示安裝了Tomcat,這裏我們就不在演示,不清楚的博友可以參考這篇博文,http://freeloda.blog.51cto.com/2033581/1299644,在上一篇博文中我們沒有增加,SysV腳本,在這篇博文中我們來增加一下,下面我們就來具體演示一下。

[root@tomcat ~]# vim /etc/init.d/tomcat
#!/bin/sh
# Tomcat init script for Linux.
#
# chkconfig: 2345 96 14
# description: The Apache Tomcat servlet/JSP container.
CATALINA_HOME=/usr/local/tomcat #注意你的腳本路徑
export CATALINA_HOME
# export CATALINA_OPTS="-Xms128m -Xmx256m"

exec $CATALINA_HOME/bin/catalina.sh $*

#############  jdk 的路徑以上已經選擇默認的 /usr ,所以如果有特殊情況,需要如下  ##############

#!/bin/sh
# Tomcat init script for Linux.
#
# chkconfig: 2345 96 14
# description: The Apache Tomcat servlet/JSP container.
JAVA_HOME=/root/packages/jdk1.7.0_07
CATALINA_HOME=/root/packages/tomcat6.0
export CATALINA_HOME JAVA_HOME
# export CATALINA_OPTS="-Xms128m -Xmx256m"
exec $CATALINA_HOME/bin/catalina.sh $*

下面我們來增加執行權限,並加入服務列表設置開機自啓動,

[root@tomcat ~]# chmod +x /etc/init.d/tomcat
[root@tomcat ~]# chkconfig --add tomcat
[root@tomcat ~]# chkconfig tomcat --list

tomcat 0:關閉 1:關閉 2:啓用 3:啓用 4:啓用 5:啓用 6:關閉

下面我們來啓動一下Tomcat並測試一下,

[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

查看一下啓動的端口號,

[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1044/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1121/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   12988/sshd
tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   13053/sshd
tcp    0   0 :::8080           :::*            LISTEN   13088/java
tcp    0   0 :::22            :::*            LISTEN   1044/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1121/master
tcp    0   0 ::1:6010          :::*            LISTEN   12988/sshd
tcp    0   0 ::1:6011          :::*            LISTEN   13053/sshd
tcp    0   0 ::ffff:127.0.0.1:8005    :::*            LISTEN   13088/java
tcp    0   0 :::8009           :::*            LISTEN   13088/java

用瀏覽器訪問一下,

好了,到這裏Tomcat的SysV腳本增加完成,下面我們來說一下catalina腳本。

2.catalina 腳本講解

首先我們來查看一下這個腳本,

[root@tomcat bin]# catalina.sh -h
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Usage: catalina.sh ( commands ... )
commands:
 debug       Start Catalina in a debugger
 debug -security  Debug Catalina with a security manager
 jpda start    Start Catalina under JPDA debugger
 run        Start Catalina in the current window
 run -security   Start in the current window with security manager
 start       Start Catalina in a separate window
 start -security  Start in a separate window with security manager
 stop       Stop Catalina, waiting up to 5 seconds for the process to end
 stop n      Stop Catalina, waiting up to n seconds for the process to end
 stop -force    Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
 stop n -force   Stop Catalina, wait up to n seconds and then use kill -KILL if still running
 configtest    Run a basic syntax check on server.xml - check exit code for result
 version      What version of tomcat are you running?
Note: Waiting for the process to end and use of the -force option require that $CATALINA_PID is defined

注,從幫助上來看,這個腳本使用還是挺簡單的。下面我們來說幾個常用的選項,

catalina.sh

下面我們就來具體演示一下,

[root@tomcat ~]# catalina.sh configtest
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
九月 21, 2013 11:08:26 下午 org.apache.catalina.core.AprLifecycleListener init
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
九月 21, 2013 11:08:27 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-bio-8080"]
九月 21, 2013 11:08:27 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-bio-8009"]
九月 21, 2013 11:08:27 下午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1269 ms

注,使用configtest選項時,得關閉Tomcat,不然會報錯。

啓動Tomcat,

[root@tomcat ~]# catalina.sh start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

關閉Tomcat,

[root@tomcat ~]# catalina.sh stop
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

查看Tomcat版本,

[root@tomcat ~]# catalina.sh version
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.42
Server built:  Jul 2 2013 08:57:41
Server number: 7.0.42.0
OS Name:    Linux
OS Version:   2.6.32-358.el6.x86_64
Architecture:  amd64
JVM Version:  1.7.0_40-b43
JVM Vendor:   Oracle Corporation

好了,catalina腳本,我們就說到這裏了,下面我們來說一下telnet管理Tomcat。

3.telnet 登錄管理Tomcat

注,在說telnet管理Tomcat之前,我們得先看一下默認的配置文件,這裏面定義了默認的管理端口,

[root@tomcat ~]# vim /usr/local/tomcat/conf/server.xml
<Server port="8005" shutdown="SHUTDOWN">

說明,定義了一個管理端口爲8005,我們可以用telnet直接登錄進本機的8005端口,來執行SHUTDOWN命令,來關閉Tomcat實例。下面我們來具體演示一下,

先安裝telnet客戶端,

[root@tomcat ~]# yum install -y telnet

下面我們一測試並查看,

[root@tomcat ~]# telnet localhost 8005
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
SHUTDOWN #輸入SHOWDOWN就可以直接關閉Tomcat服務
Connection closed by foreign host.
[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1044/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1121/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   12988/sshd
tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   13053/sshd
tcp    0   0 :::22            :::*            LISTEN   1044/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1121/master
tcp    0   0 ::1:6010          :::*            LISTEN   12988/sshd
tcp    0   0 ::1:6011          :::*            LISTEN   13053/sshd

注,大家可以看到Tomcat服務已經關閉。好了,telnet管理我們就說到這裏,下面我們來說一下,Tomcat虛擬主機的配置

4.配置Tomcat虛擬主機

注,在說Tomcat虛擬主機之前,咱們來詳細的看看默認的配置文件,雖然在上一篇博客中全部有講解,在這篇博客中我還是再和大家簡單說一下,下面是默認配置文件。大家可以看到,絕大部分的配置文件是註釋,包含在<!---->、全是註釋。下面我們就來具體的看看,註釋我們就不說了,說具體的定義的內容

[root@tomcat ~]# cat /usr/local/tomcat/conf/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="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"> #定義一個Service命令爲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"
        redirectPort="8443" /> #這裏定義了一個連接器,協議爲http,端口爲8080,最大連接超時爲20s,這裏還定義了一個SSL的重定向端口8443。我們可以根據需要進行修改。一般我們都用80端口與443端口。
  <!-- 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 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" /> #這裏定義了一個SSL的案例,主要定義相關密鑰與證書。
  -->
  <!-- Define an AJP 1.3 Connector on port 8009 -->
  <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> #這裏定義了一個支持AJP協議的連接器。
  <!-- 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"> #這裏定義了一個名爲Catalina的引擎,並定義了一個默認主機爲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>

好了,在這裏我們又簡單的說明一下,配置文件下面我們就來具體演示一下怎麼配置虛擬主機。

首先,我們來修改一下配置文件,

[root@tomcat conf]# vim server.xml

#增加下面幾行

<Host name="www.test.com" appBase="/web/webapp"
   unpackWARs="true" autoDeploy="true">
     <Context path="/" docBase="/web/webapp" reloadable="true"/>
</Host>

接下來我們來創建文檔目錄與測試頁面,

[root@tomcat ~]# mkdir -pv /web/webapp
[root@tomcat ~]# cd /web/webapp
[root@tomcat webapp]# vim index.jsp
<%@ page language="java" %>
<%@ page import="java.util.*" %>
<html>
 <head>
  <title>JSP test page.</title>
 </head>
 <body>
  <% out.println("Welcome to test. Site, http://www.test.com"); %>
 </body>
</html>

現在我們來測試一下我們修改的配置文件,

[root@tomcat ~]# service tomcat stop
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
^[[A[root@tomcat service tomcat configtest
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Sep 22, 2013 2:15:47 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 22, 2013 2:15:47 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
Sep 22, 2013 2:15:47 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 22, 2013 2:15:47 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1294 ms

注,大家可以看到,我們這裏沒有報錯,說明配置都是正確的,若配置有錯誤,會在最後一行提醒你。

再下面我們來啓動Tomcat並測試一下,

[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp Active Internet connections (onlyservers) Proto Recv-Q Send-Q Local Address Foreign Address StatePID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1044/sshd tcp0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0127.0.0.1:6010 0.0.0.0:* LISTEN 13368/sshd tcp 0 0 127.0.0.1:60110.0.0.0:* LISTEN 13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN13407/sshd tcp 0 0 :::80 :::* LISTEN 13557/java tcp 0 0 :::22 :::*LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp 0 0::1:6010 :::* LISTEN 13368/sshd tcp 0 0 ::1:6011 :::* LISTEN13387/sshd tcp 0 0 ::1:6012 :::* LISTEN 13407/sshd tcp 0 0 :::8009:::* LISTEN 13557/java

注,還有一點得說明一下,我這裏爲了方便測試,將默認端口8080修改爲了80端口。下面是測試效果,

爲了幫助大家理解,我們這裏再次講解一下,Host組件與Context組件以及相關屬性。

Host組件:

位於Engine容器中用於接收請求並進行相應處理的主機或虛擬主機,如前面我們自定義的內容:

<Host name="www.server110.com" appBase="/web/webapp"
   unpackWARs="true" autoDeploy="true">
     <Context path="/" docBase="/web/webapp" reloadable="true"/>
</Host>

常用屬性說明:

name:定義虛擬主機的域名

appBase:此Host的webapps目錄,即存放非歸檔的web應用程序的目錄或歸檔後的WAR文件的目錄路徑;可以使用基於$CATALINA_HOME的相對路徑;

autoDeploy:在Tomcat處於運行狀態時放置於appBase目錄中的應用程序文件是否自動進行deploy;默認爲true;

unpackWars:在啓用此webapps時是否對WAR格式的歸檔文件先進行展開;默認爲true;

主機別名定義:

如果一個主機有兩個或兩個以上的主機名,額外的名稱均可以以別名的形式進行定義,如下:

<Host name="www.test.com" appBase="webapps" unpackWARs="true">
 <Alias>web.test.com</Alias>
</Host>
Context組件:
Context在某些意義上類似於apache中的路徑別名,一個Context定義用於標識tomcat實例中的一個Web應用程序。如下面的定義:
  <!-- Tomcat Root Context -->
  <Context path="" docBase="/web/webapps"/>
  <!-- buzzin webapp -->
  <Context path="/bbs"
   docBase="/web/threads/bbs"
   reloadable="true">
  </Context>
  <!-- chat server -->
   <Context path="/chat" docBase="/web/chat"/>
  <!-- darian web -->
  <Context path="/darian" docBase="darian"/>

在Tomcat中,每一個context定義也可以使用一個單獨的XML文件進行,其文件的目錄爲$CATALINA_HOME/conf/<enginename>/<hostname>。可以用於Context中的XML元素有Loader,Manager,Realm,Resources和WatchedResource。

常用的屬性定義有:

docBase:相應的Web應用程序的存放位置;也可以使用相對路徑,起始路徑爲此Context所屬Host中appBase定義的路徑;切記,docBase的路徑名不能與相應的Host中appBase中定義的路徑名有包含關係,比如,如果appBase爲deploy,而docBase絕不能爲deploy-bbs類的名字;

path:相對於Web服務根路徑而言的URI;如果爲空“”,則表示爲此webapp的根路徑;如果context定義在一個單獨的xml文件中,此屬性不需要定義;

reloadable:是否允許重新加載此context相關的Web應用程序的類;默認爲false;

爲了便於大家理解,我們這裏再定義一個Context並測試一下,

我們先來修改一下配置文件

[root@tomcat conf]# vim server.xml
<Host name="www.test.com" appBase="/web/webapp"
    unpackWARs="true" autoDeploy="true">
      <Context path="/" docBase="/web/webapp" reloadable="true"/>
      <Context path="/test" docBase="/web/test" reloadable="true"/> #增加這一行
 </Host>

下面來增加目錄文檔與測試文件,

[root@tomcat webapp]# mkdir /web/test
[root@tomcat webapp]# cd /web/test
[root@tomcat test]# vim index.jsp
<%@ page language="java" %>
<html>
 <head><title>TomcatA</title></head>
 <body>
  <h1><font color="red">TomcatA </h1>
  <table align="centre" >
   <tr>
    <td>Session ID</td>
  <% session.setAttribute("abc","abc"); %>
    <td><%= session.getId() %></td>
   </tr>
   <tr>
    <td>Created on</td>
    <td><%= session.getCreationTime() %></td>
   </tr>
  </table>
 </body>
</html>

測試一下配置文件是否有錯並啓動Tomcat,

[root@tomcat ~]# service tomcat configtest Using CATALINA_BASE:/usr/local/tomcat Using CATALINA_HOME: /usr/local/tomcat UsingCATALINA_TMPDIR: /usr/local/tomcat/temp Using JRE_HOME: /usr UsingCLASSPATH:/usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jarSep 22, 2013 2:40:57 AMorg.apache.catalina.core.AprLifecycleListener init INFO: The APRbased Apache Tomcat Native library which allows optimal performancein production environments was not found on the java.library.path:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib Sep22, 2013 2:40:58 AM org.apache.coyote.AbstractProtocol init INFO:Initializing ProtocolHandler ["http-bio-80"] Sep 22, 2013 2:40:58AM org.apache.coyote.AbstractProtocol init INFO: InitializingProtocolHandler ["ajp-bio-8009"] Sep 22, 2013 2:40:58 AMorg.apache.catalina.startup.Catalina load INFO: Initializationprocessed in 1352 ms
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp Active Internet connections (onlyservers) Proto Recv-Q Send-Q Local Address Foreign Address StatePID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1044/sshd tcp0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0127.0.0.1:6010 0.0.0.0:* LISTEN 13587/sshd tcp 0 0 127.0.0.1:60110.0.0.0:* LISTEN 13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN13407/sshd tcp 0 0 :::80 :::* LISTEN 13945/java tcp 0 0 :::22 :::*LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp 0 0::1:6010 :::* LISTEN 13587/sshd tcp 0 0 ::1:6011 :::* LISTEN13387/sshd tcp 0 0 ::1:6012 :::* LISTEN 13407/sshd tcp 0 0::ffff:127.0.0.1:8005 :::* LISTEN 13945/java tcp 0 0 :::8009 :::*LISTEN 13945/java

下面我們就用瀏覽器測試一下,

好了,到這裏我們的Tomcat虛擬主機的講解就到這裏了,下面我們來說一下Tomcat圖形管理接口。

5.Tomcat圖形管理接口

我們先來看一下默認的圖形配置界面,

注,大家注意看右上角,我用紅色方框標記出來的,大家可以看有三個按鈕,分別爲

Server Status 主要用來查看服務的狀態

Manager App 主要用來管理應用程序的部署及監控

Host Manager 主要用來管理虛擬主機

下面我們就來具休的配置一下,大家可以看到,你點擊任何一個按鈕都要輸入用戶名和密碼的,在我們配置之前我們先來說一下,Tomcat的Manager功能,

Manager的四個管理角色:

manager-gui - allows access to the HTML GUI and the statuspages

manager-script - allows access to the text interface and thestatus pages

manager-jmx - allows access to the JMX proxy and the statuspages

manager-status - allows access to the status pages only

注,這裏我說一下,上面的英文比較簡單我就不在裏翻譯了,大家自己看一下。

下面我們就來啓用manager功能,修改tomcat-user.xml文件,添加如下行:

<role rolename="manager-gui"/>
<role rolename="admin-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui,admin-gui"/>

簡單解釋一下,Tomcat有內置的角色,我們這裏增加了兩個角色一個爲manager-gui,另一個爲admin-gui,用戶名和密碼都爲tomcat。

注,增加的內容一定要在<tomcat-users></tomcat-users>之間。不然,不會生效。好了,下面我們一來測試一下配置文件,並重新啓動一下Tomcat

[root@tomcat ~]# service tomcat configtest Using CATALINA_BASE:/usr/local/tomcat Using CATALINA_HOME: /usr/local/tomcat UsingCATALINA_TMPDIR: /usr/local/tomcat/temp Using JRE_HOME: /usr UsingCLASSPATH:/usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jarSep 22, 2013 3:08:44 AMorg.apache.catalina.core.AprLifecycleListener init INFO: The APRbased Apache Tomcat Native library which allows optimal performancein production environments was not found on the java.library.path:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib Sep22, 2013 3:08:44 AM org.apache.coyote.AbstractProtocol init INFO:Initializing ProtocolHandler ["http-bio-80"] Sep 22, 2013 3:08:44AM org.apache.coyote.AbstractProtocol init INFO: InitializingProtocolHandler ["ajp-bio-8009"] Sep 22, 2013 3:08:44 AMorg.apache.catalina.startup.Catalina load INFO: Initializationprocessed in 1213 ms
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp Active Internet connections (onlyservers) Proto Recv-Q Send-Q Local Address Foreign Address StatePID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1044/sshd tcp0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0127.0.0.1:6010 0.0.0.0:* LISTEN 13587/sshd tcp 0 0 127.0.0.1:60110.0.0.0:* LISTEN 13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN13407/sshd tcp 0 0 :::80 :::* LISTEN 14197/java tcp 0 0 :::22 :::*LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp 0 0::1:6010 :::* LISTEN 13587/sshd tcp 0 0 ::1:6011 :::* LISTEN13387/sshd tcp 0 0 ::1:6012 :::* LISTEN 13407/sshd tcp 0 0::ffff:127.0.0.1:8005 :::* LISTEN 14197/java tcp 0 0 :::8009 :::*LISTEN 14197/java

好了,下面我們用瀏覽器查看一下,

注,點擊Server Status按鈕,讓你輸入用戶名和密碼。我這裏全部設置是tomcat。

然後,會出現以下界面。顯示全部服務運行狀態!大家可以仔細的看一下,我就不帶着大家看了。

下面是應用程序部署管理界面,

下面是虛擬主機管理頁面,

注,我們一般在生產環境中用的最多是應用程序部署界面,可以進行熱佈署應用程序,很方便,大家可以嘗試一下。好了,圖形管理界面我們就說到這裏了,下面我們來說一下,Tomcat的一個小案例。我們說了那麼多,有朋友就會說了,怎麼一個案例也沒有呢?下面我們就來佈署一個社交網站的案例JavaCenterHome。

6.部署JSP網站案例

首頁,我們來修改一下配置文件,

[root@tomcat conf]# vim server.xml
<Host name="www.test.com" appBase="/web"
   unpackWARs="true" autoDeploy="true">
 <Context path="/" docBase="webapp" reloadable="true"/>
</Host>

注,增加一下虛擬主機,文件目錄爲/web/webapp。

下面我們來解壓一下我們下載好的JavaCenter Home網站程序,

[root@tomcat src]# tar xf JavaCenter_Home_2.0_GBK.tar.bz2

接下來將解壓好的JavaCenter Home程序移動到/web/webapp下,

[root@tomcat src]# cd JavaCenter_Home_2.0_GBK
[root@tomcat JavaCenter_Home_2.0_GBK]# mv * /web/webapp/

下面我們來測試一下配置文件並啓動Tomcat服務

[root@tomcat ~]# service tomcat configtest
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Sep 23, 2013 5:31:18 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/jdk1.6.0_21/jre/lib/amd64/server:/usr/java/jdk1.6.0_21/jre/lib/amd64:/usr/java/jdk1.6.0_21/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 23, 2013 5:31:20 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
Sep 23, 2013 5:31:20 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 23, 2013 5:31:20 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2493 ms
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1026/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1256/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1339/sshd
tcp    0   0 0.0.0.0:3306        0.0.0.0:*          LISTEN   1165/mysqld
tcp    0   0 :::80            :::*            LISTEN   1499/java
tcp    0   0 :::22            :::*            LISTEN   1026/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1256/master
tcp    0   0 ::1:6010          :::*            LISTEN   1339/sshd
tcp    0   0 :::8009           :::*            LISTEN   1499/java

下面我們用瀏覽器訪問一下,http://www.test.com(注,要想用域名訪問,必須配置本機有hosts文件,Windows7hosts文件目錄,C:\Windows\System32\drivers\etc\hosts)

注,上面的錯誤說明我們連接Mysql數據庫失敗。因爲我們這裏還沒有安裝與配置嘛。下面我們趕快來配置一下,

先安裝數據庫,我們這裏就用yum安裝一下,

[root@tomcat ~]# yum install -y mysql-server

下面來啓動並配置mysql,

[root@tomcat ~]# service mysqld start
Starting mysqld:                      [ OK ]
[root@tomcat ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.69 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

好了,到這裏我們mysql就安裝完成了,下面我們來看一下我們的程序目錄,

[root@tomcat ~]# cd /web/webapp/
[root@tomcat webapp]# ls
admin    avatar.jsp     data     help.jsp  js.jsp    rss.jsp  userapp.jsp
admincp.jsp config.properties do.jsp    image    link.jsp   source   WEB-INF
api     contact.jsp    editor.jsp  index.jsp  magic.jsp  space.jsp xmlrpc.jsp
app.jsp   cp.jsp       errors    install   META-INF   template
attachment  crossdomain.xml  favicon.ico invite.jsp network.jsp theme

大家可以看到裏面有個install的目錄,下面我們用瀏覽器訪問一下,http://www.test.com/install,會跳出一個安裝界面,如下圖

從圖中,我們可以看出,所以環境配置完成,都符合要求。下面我們點擊“接受授權協議,開始安裝JavaCenterHome”,會跳出下一界面,如下圖

從圖中,我們可以看出得輸入,數據庫名稱、數據庫用戶名、數據庫密碼。下面我們就來增加一下,

[root@tomcat ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 5.1.69 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database jcenter;
Query OK, 1 row affected (0.00 sec)
mysql> grant all privileges on jcenter.* to jcenter@'localhost' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> grant all privileges on jcenter.* to jcenter@'127.0.0.1' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

上面創建一個jcenter數據庫,授權訪問一個jcenter用戶,密碼爲123456。下面我們繼續配置

我們輸入剛纔設置的數據庫用戶名、數據庫密碼、數據庫名稱。點擊“設置完畢,檢測我的數據庫配置”,圖顯示的3和4會看自動進行安裝,我們只等一會即可。安裝完成的效果如下圖,

下面我們開通一個管理員空間,用戶名和密碼都爲admin,如下圖

點擊“開通管理員空間”,會跳出另一個界面,如下圖

我們點擊“進入空間首頁”,效果如下圖

好了,到這裏我們的JavaCenterHome就全部配置完成了,我們第一階段的基本配置就這裏全部完成,下面我們主要講解Nginx反向代理Tomcat服務

二、Nginx反向代理Tomcat服務

0.測試環境準備階段

下面先看一下實驗拓撲,

接着來同步各節點時間,

[root@tomcat ~]# ntpdate 202.120.2.101
[root@nginx ~]# ntpdate 202.120.2.101

下面我們來安裝nginx服務,首先來解決nginx的依賴關係,

[root@nginx ~]# yum groupinstall -y "Development Tools" "Server Platform Deveopment"
[root@nginx ~]# yum install -y openssl-devel pcre-devel

下面我們來新建nginx用戶,

[root@nginx ~]# groupadd -r -g 108 nginx
[root@nginx ~]# useradd -r -g 108 -u 108 nginx
[root@nginx ~]# id nginx
uid=108(nginx) gid=108(nginx) 組=108(nginx)

接着我們來開始編譯和安裝,

[root@nginx src]# tar xf nginx-1.4.2.tar.gz
[root@nginx src]# cd nginx-1.4.2
[root@nginx nginx-1.4.2]# ls
auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src
[root@nginx nginx-1.4.2]# ./configure \
>  --prefix=/usr \
>  --sbin-path=/usr/sbin/nginx \
>  --conf-path=/etc/nginx/nginx.conf \
>  --error-log-path=/var/log/nginx/error.log \
>  --http-log-path=/var/log/nginx/access.log \
>  --pid-path=/var/run/nginx/nginx.pid \
>  --lock-path=/var/lock/nginx.lock \
>  --user=nginx \
>  --group=nginx \
>  --with-http_ssl_module \
>  --with-http_flv_module \
>  --with-http_stub_status_module \
>  --with-http_gzip_static_module \
>  --http-client-body-temp-path=/var/tmp/nginx/client/ \
>  --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
>  --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
>  --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
>  --http-scgi-temp-path=/var/tmp/nginx/scgi \
>  --with-pcre
[root@nginx nginx-1.4.2]# make && make install

說明:

Nginx可以使用Tmalloc(快速、多線程的malloc庫及優秀性能分析工具)來加速內存分配,使用此功能需要事先安裝gperftools,而後在編譯nginx添加--with-google_perftools_module選項即可。

如果想使用nginx的perl模塊,可以通過爲configure腳本添加--with-http_perl_module選項來實現,但目前此模塊仍處於實驗性使用階段,可能會在運行中出現意外,因此,其實現方式這裏不再介紹。如果想使用基於nginx的cgi功能,也可以基於FCGI來實現,具體實現方法請參照網上的文檔。

下面我們爲nginx提供SysV init腳本,

[root@nginx ~]# cat /etc/init.d/nginx
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:  - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
#        proxy and IMAP/POP3 proxy server
# processname: nginx
# config:   /etc/nginx/nginx.conf
# config:   /etc/sysconfig/nginx
# pidfile:   /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
  # make required directories
  user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
  options=`$nginx -V 2>&1 | grep 'configure arguments:'`
  for opt in $options; do
    if [ `echo $opt | grep '.*-temp-path'` ]; then
      value=`echo $opt | cut -d "=" -f 2`
      if [ ! -d "$value" ]; then
        # echo "creating" $value
        mkdir -p $value && chown -R $user $value
      fi
    fi
  done
}
start() {
  [ -x $nginx ] || exit 5
  [ -f $NGINX_CONF_FILE ] || exit 6
  make_dirs
  echo -n $"Starting $prog: "
  daemon $nginx -c $NGINX_CONF_FILE
  retval=$?
  echo
  [ $retval -eq 0 ] && touch $lockfile
  return $retval
}
stop() {
  echo -n $"Stopping $prog: "
  killproc $prog -QUIT
  retval=$?
  echo
  [ $retval -eq 0 ] && rm -f $lockfile
  return $retval
}
restart() {
  configtest || return $?
  stop
  sleep 1
  start
}
reload() {
  configtest || return $?
  echo -n $"Reloading $prog: "
  killproc $nginx -HUP
  RETVAL=$?
  echo
}
force_reload() {
  restart
}
configtest() {
 $nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
  status $prog
}
rh_status_q() {
  rh_status >/dev/null 2>&1
}
case "$1" in
  start)
    rh_status_q && exit 0
    $1
    ;;
  stop)
    rh_status_q || exit 0
    $1
    ;;
  restart|configtest)
    $1
    ;;
  reload)
    rh_status_q || exit 7
    $1
    ;;
  force-reload)
    force_reload
    ;;
  status)
    rh_status
    ;;
  condrestart|try-restart)
    rh_status_q || exit 0
      ;;
  *)
    echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
    exit 2
esac

而後爲此腳本賦予執行權限,

[root@nginx ~]# chmod +x /etc/init.d/nginx

添加至服務管理列表,並讓其開機自動啓動,

[root@nginx ~]# chkconfig --add nginx
[root@nginx ~]# chkconfig nginx on

而後就可以啓動服務並測試了,

[root@nginx ~]# service nginx start
正在啓動 nginx:                      [確定]
[root@nginx ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:80         0.0.0.0:*          LISTEN   14006/nginx
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1029/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1105/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1345/sshd
tcp    0   0 :::22            :::*            LISTEN   1029/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1105/master
tcp    0   0 ::1:6010          :::*            LISTEN   1345/sshd

下面是測試結果,

好了,到這裏我們準備工作就全部完成了,下面們來簡單的配置一下Nginx反向代理Tomcat服務

1.Nginx將請求反向代理到後端Tomcat

首先,我們來修改一下nginx的配置文件,

[root@nginx ~]# cd /etc/nginx/
[root@nginx nginx]# cp nginx.conf nginx.conf.bak
[root@nginx nginx]# vim nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log logs/access.log main;
  sendfile    on;
  #tcp_nopush   on;
  #keepalive_timeout 0;
  keepalive_timeout 65;
  #gzip on;
  server {
    listen    80;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      #root  html;
      #index index.html index.htm;
      proxy_pass http://192.168.18.201/; #註釋默認兩行,新增一行。
    }
    #error_page 404       /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }
}

重新加載一下配置文件,

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新載入 nginx:                      [確定]

下面進行測試一下,(注,首先你得保證你的tomcat服務能正常訪問,下面我們先來訪問一下tomcat服務,如下圖)

大家可以看到我們的tomcat服務可以正常訪問,下面我們來看測試一下nginx可不可以進行反向代理。(注,還有問題,這裏爲了方便測試我們先將tomcat的默認主機設置爲www.test.com)

[root@tomcat ~]# vim /usr/local/tomcat/conf/server.xml
  <Engine name="Catalina" defaultHost="www.test.com">

重新啓動一下tomcat並測試,

[root@tomcat ~]# service tomcat stop
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1026/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1256/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1339/sshd
tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   2744/sshd
tcp    0   0 0.0.0.0:3306        0.0.0.0:*          LISTEN   2382/mysqld
tcp    0   0 :::80            :::*            LISTEN   3299/java
tcp    0   0 :::22            :::*            LISTEN   1026/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1256/master
tcp    0   0 ::1:6010          :::*            LISTEN   1339/sshd
tcp    0   0 ::1:6011          :::*            LISTEN   2744/sshd
tcp    0   0 :::8009           :::*            LISTEN   3299/java

下面我們來訪問測試一下tomcat服務

下面我們來測試看nginx是否能代理tomcat服務

好了,大家可以看到我們成功設置了nginx反向代理tomcat服務。好了,大家可以看到,我們網站上有很多的圖片,每次訪問都要去後端的tomcat服務上去取,很消耗服務資源。我們下面將設置在nginx服務上緩存圖片。

2.Nginx將圖片緩存到本地

同樣的,我們先來修改配置文件,

[root@nginx nginx]# cat nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log logs/access.log main;
  sendfile    on;
  #tcp_nopush   on;
  #keepalive_timeout 0;
  keepalive_timeout 65;
  #gzip on;
  proxy_cache_path /nginx/cache levels=1:2 keys_zone=first:10m inactive=24h max_size=1G; #新建緩存路徑與相關屬性
  upstream backend { #建立後端tomcat服務
  server 192.168.18.201 weight=1;
  }
  server {
    listen    80;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      #root  html;
      #index index.html index.htm;
      #proxy_pass http://192.168.18.201/; #註釋原來的代理設置
      proxy_pass http://backend/; #啓動後端服務
    }
  location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" { #緩存圖片與靜態內容
    proxy_pass http://backend;
    proxy_cache first;
    proxy_cache_valid 200 24h; #200狀態緩存24小時
    proxy_cache_valid 302 10m; #302狀態緩存10分鐘
    add_header X-Cache-Status $upstream_cache_status; #在http頭部增加一個字段顯示是否命令緩存
  }
    #error_page 404       /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }
}

下面我們來新建緩存目錄,

[root@nginx ~]# mkdir -pv /nginx/cache
mkdir: 已創建目錄 "/nginx"
mkdir: 已創建目錄 "/nginx/cache"

測試一下配置文件是否有錯,

[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新加載配置文件,

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新載入 nginx:                      [確定]

那麼下面我們就來測試一下,

大家可以看到我們訪問的所有的靜態內容都是命中的,X-Cache-Status: HIT,下面們來看一下緩存的目錄,

[root@nginx ~]# cd /nginx/cache/
[root@nginx cache]# ls
0 1 2 3 4 5 6 7 8 9 b c d e

大家可以看到,緩存目錄當中有我們緩存的內容,好了到這裏我們的nginx緩存服務配置完成了,下面我們看一下如何實現動靜分離。

3.Nginx將請求實現動靜分離

首先,我們來說一下我們要實現的效果,上面我們已經將靜態內容緩存在nginx服務上,我們想讓用戶請求的靜態內容到nginx去取,動態內容到tomcat服務上去取,這就能實現動靜分享效果。同樣的首先我們來修改配置文件,

[root@nginx nginx]# cat nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log logs/access.log main;
  sendfile    on;
  #tcp_nopush   on;
  #keepalive_timeout 0;
  keepalive_timeout 65;
  #gzip on;
  proxy_cache_path /nginx/cache levels=1:2 keys_zone=first:10m inactive=24h max_size=1G;
  upstream backend {
  server 192.168.18.201 weight=1;
  }
  server {
    listen    80;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
  index index.jsp index.html;
    location ~* "\.(jsp|do)$" { #當請求的是jsp或do文件時直接到tomcat上去取
      #root  html;
      #index index.html index.htm;
      #proxy_pass http://192.168.18.201/;
      #proxy_pass http://backend/;
      proxy_pass http://backend;
    }
  location = / {
    root html;
    rewrite ^/ http://192.168.18.201/index.jsp last;
  }
  location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" {
    proxy_pass http://backend;
    proxy_cache first;
    proxy_cache_valid 200 24h;
    proxy_cache_valid 302 10m;
    add_header X-Cache-Status $upstream_cache_status;
  }
    #error_page 404       /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }
}

下面我們來檢查一下配置文件是否有誤,

[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新加載一下配置文件,

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新載入 nginx:                      [確定]

下面我們來訪問測試一下,

大家可以看到我們的靜態內容來自緩存,動態內容全部代理到後端的tomcat服務上了,說明我們動態分離配置完成,好了到這裏我們的tomcat的基本配置與nginx反向代理tomcat的配置就全部完成了,最後希望大家有所收穫^_^……

發佈了237 篇原創文章 · 獲贊 18 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章