Nginx 快速入门笔记(带jdk1.8、tomcat、以及相关环境配置介绍)

Nginx 快速入门笔记(带jdk1.8、tomcat、以及相关环境配置介绍 )

image-20200702181036298

内容介绍

nginx
1、 nginx 简介
    (1) 什么是 nginx 和可以做什么事情
    (2) 正向代理
    (3) 反向代理
    (4) 动静分离
    
2、 Nginx 的安装
    (1) 在 linux 系统中安装 nginx
    
3、 Nginx 的常用命令和配置文件

4、 Nginx 配置实例 1 反向代理

5、 Nginx 配置实例 2 负载均衡

6、 Nginx 配置实例 3 动静分离

7、 Nginx 的高可用集群
    (1) nginx 配置主从模式
    (2) nginx 配置双主模式

Nginx 的简介

1. 什么是 nginx

​ Nginx 可以作为静态页面的 web 服务器,同时还支持 CGI 协议的动态语言,比如 perl、php等。但是不支持 java。Java 程序只能通过与 tomcat 配合完成。Nginx 专为性能优化而开发,性能是其最重要的考量,实现上非常注重效率 ,能经受高负载的考验,有报告表明能支持高达 50,000 个并发连接数。

https://lnmp.org/nginx.html

2. 正向代理

​ Nginx 不仅可以做反向代理,实现负载均衡。还能用作正向代理来进行上网等功能。

正向代理:如果把局域网外的 Internet 想象成一个巨大的资源库,则局域网中的客户端要访问 Internet,则需要通过代理服务器来访问,这种代理服务就称为正向代理。

(1)需要在客户端配置代理服务器进行指定网站访问 :

image-20200702182111135

image-20200702183146270

3. 反向代理

反向代理 : 其实客户端对代理是无感知的,因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器 IP 地址

image-20200702182303173

image-20200702182303173

4. 负载均衡

​ 客户端发送多个请求到服务器,服务器处理请求,有一些可能要与数据库进行交互,服务器处理完毕后,再将结果返回给客户端。

	这种架构模式对于早期的系统相对单一,并发请求相对较少的情况下是比较适合的,成本也低。但是随着信息数量的不断增长,访问量和数据量的飞速增长,以及系统业务的复杂度增加,这种架构会造成服务器相应客户端的请求日益缓慢,并发量特别大的时候,还容易造成服务器直接崩溃。很明显这是由于服务器性能的瓶颈造成的问题,那么如何解决这种情况呢?

	我们首先想到的可能是升级服务器的配置,比如提高 CPU 执行频率,加大内存等提高机器的物理性能来解决此问题,但是我们知道摩尔定律的日益失效,硬件的性能提升已经不能满足日益提升的需求了。最明显的一个例子,天猫双十一当天,某个热销商品的瞬时访问量是极其庞大的,那么类似上面的系统架构,将机器都增加到现有的顶级物理配置,都是不能够满足需求的。那么怎么办呢?

​ 上面的分析我们去掉了增加服务器物理配置来解决问题的办法,也就是说纵向解决问题的办法行不通了,那么横向增加服务器的数量呢?这时候集群的概念产生了,单个服务器解决不了,我们增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的情况改为将请求分发到多个服务器上,将负载分发到不同的服务器,也就是我们所说的负载均衡

image-20200702182444912

image-abcdre

5. 动静分离

​ 为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度。降低原来单个服务器的压力。

image-20200702183722386

image-20200702193541871

Nginx 的安装

1. 进入 nginx 官网,下载

http://nginx.org/

image-20200702195847326

image-20200702195907197

2. 安装nginx

第一步,安装 pcre

wget http://downloads.sourceforge.net/project/pcre/pcre/8.37/pcre-8.37.tar.gz

image-20200702214237180

解压文件:tar -xvf pcre-8.37.tar.gz

image-20200702214750462

进入解压缩的 pcre-8.37 执行 ./configure

image-20200702215042015

./configure 执行完成后,回到 pcre 目录下执行 make && make install

image-20200702220251861

查看版本号 判断是否成功 pcre-config --version

image-20200702220357702

第二步,安装 openssl
第三步,安装 zlib

yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel

image-20200702220554120

第四步,安装nginx

image-20200702220819387

压缩包放入usr/src下,并解压 tar -xvf nginx-1.18.0.tar.gz

image-20200702220929023

进入nginx目录下执行 ./configure

image-20200702221038872

执行完后 再执行 make && make install

安装成功后 usr/local 下会增一个 nginx 文件夹

image-20200702221329693

测试启动 nginx 并在进程中查看

image-20200702221513893

在nginx 目录的 conf 目录下的nginx.conf 可以查看端口号,默认是80

命令:vi nginx.conf

浏览器直接通过ip地址访问,测试能否成功!(这里如果访问不成,进不去,要考虑是否将防火墙关闭!)

image-20200702223837603

防火墙配置(开放端口号)

查看防火墙开放的端口号

firewall-cmd --list-all

设置开放的端口号

firewall-cmd --add-service=http –permanent

sudo firewall-cmd --add-port=80/tcp --permanent

重启防火墙

firewall-cmd –reload

nginx 常用操作命令和配置文件

启动命令

在/usr/local/nginx/sbin 目录下执行 ./nginx

关闭命令

在/usr/local/nginx/sbin 目录下执行 ./nginx -s stop

重新加载命令

在/usr/local/nginx/sbin 目录下执行 ./nginx -s reload

nginx.conf 配置文件

image-20200702224558624

​ nginx 安装目录下,其默认的配置文件都放在这个目录的 conf 目录下,而主配置文件nginx.conf 也在其中,后续对 nginx 的使用基本上都是对此配置文件进行相应的修改。

​ 配置文件中有很多#, 开头的表示注释内容,我们去掉所有以 # 开头的段落,精简之后的内容如下:

#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;
        }

        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
    
    
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
    
    
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
 }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    
    
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    
    
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

根据上述文件,我们可以很明显的将 nginx.conf 配置文件分为三部分:

第一部分:全局块

​ 从配置文件开始到 events 块之间的内容,主要会设置一些影响 nginx 服务器整体运行的配置指令,主要包括:配置运行 Nginx 服务器的用户(组)、允许生成的 worker process 数,进程 PID 存放路径、日志存放路径和类型以及配置文件的引入等

比如上面第一行配置的:

#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;

​ 这是 Nginx 服务器并发处理服务的关键配置,worker_processes 值越大,可以支持的并发处理量也越多,但是会受到硬件、软件等设备的制约。

第二部分:events 块

比如上面的配置:

events {
    
    
    worker_connections  1024;
}

​ events 块涉及的指令主要影响 Nginx 服务器与用户的网络连接,常用的设置包括是否开启对多 work process 下的网络连接进行序列化,是否允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个 word process 可以同时支持的最大连接数等。

​ 上述例子就表示每个 work process 支持的最大连接数为 1024。

	这部分的配置对 Nginx 的性能影响较大,在实际中应该灵活配置。
第三部分:http 块
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;
        }

        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
    
    
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
    
    
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
 }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    
    
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    
    
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

​ 这算是 Nginx 服务器配置中最频繁的部分,代理、缓存和日志定义等绝大多数功能和第三方模块的配置都在这里。

需要注意的是:http 块也可以包括 http 全局块server 块

http 全局块

​ http 全局块配置的指令包括文件引入、MIME-TYPE 定义、日志自定义、连接超时时间、单链接请求数上限等。

server 块

​ 这块和虚拟主机有密切关系,虚拟主机从用户角度看,和一台独立的硬件主机是完全一样的,该技术的产生是为了节省互联网服务器硬件成本。

​ 每个 http 块可以包括多个 server 块,而每个 server 块就相当于一个虚拟主机。

​ 而每个 server 块也分为全局 server 块,以及可以同时包含多个 locaton 块。

	**1、全局 server 块**

​ 最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或 IP 配置。

2、location 块

​ 一个 server 块可以配置多个 location 块。

​ 这块的主要作用是基于 Nginx 服务器接收到的请求字符串(例如 server_name/uri-string),对虚拟主机名称(也可以是 IP 别名)之外的字符串(例如 前面的 /uri-string)进行匹配,对特定的请求进行处理。地址定向、数据缓存和应答控制等功能,还有许多第三方模块的配置也在这里进行。

nginx 配置实例-反向代理

反向代理实例一

实现效果:使用 nginx 反向代理,访问 www.123.com 直接跳转到 127.0.0.1:8080

具体步骤:

1. 安装tomcat

image-20200703103009308

解压缩命令:tar -xvf apache-tomcat-7.0.70.tar.gz

2. 安装jdk(并配置环境变量)

首先查看linux 是否自带jdk

java -version : 如果显示jdk版本号,则说明自带有jdk,无需要额外安装

image-20200703103713280

如果不显示,就需要安装jdk1.8 并配置环境变量:

2.1 下载jdk1.8

下载地址 http://www.oracle.com/technetwork/java/javase/downloads/index.html

往下来拉找到jdk1.8版本的下载地址,点击下载对应的tar.gz文件:

image-20200703103947734

image-20200703104255517

将下载的jdk 压缩包放入 usr/src 下

2.2 解压jdk压缩包

命令:tar -zxvf jdk-8u251-linux-x64.tar.gz

image-20200703105152410

2.3 配置jdk环境变量

键入命令 vim /etc/profile 修改配置文件,记得要在root权限下修改

输入i进入编辑状态,然后将光标移到最后一行(GG最后一行 gg第一行),粘贴如下内容:

JAVA_HOME=/usr/src/jdk1.8.0_251		##要根据自己的解压目录设置

具体内容如下:

#java environment
export JAVA_HOME=/usr/src/jdk1.8.0_251
export CLASSPATH=.:${JAVA_HOME}/jre/lib/rt.jar:${JAVA_HOME}/lib/dt.jar:${JAVA_HOME}/lib/tools.jar

export PATH=$PATH:${JAVA_HOME}/bin

效果如下:

image-20200703105959579

然后键入命令source /etc/profile 使配置文件生效

2.4 测试安装效果

java -version

image-20200703110120909

显示上图则jdk 配置完成!

3. 启动 tomcat

image-20200703110353819

启动步骤如上图所示,测试访问(这里需要注意,如果访问不成功,就有可能是你的linux 防火墙没有开8080端口,需要修改下防火墙端口配置):

开放端口8080
sudo firewall-cmd --add-port=8080/tcp --permanent
重启防火墙
firewall-cmd –reload
查看已经开放的端口
firewall-cmd --list-all
测试

image-20200703110625590

访问成功!

4. 反向代理访问过程分析

image-20200703111854097

5. 配置反向代理步骤
5.1 本机 host 文件配置

在本机windows 系统的 host 文件进行域名和ip 对应关系的配置。

image-20200703112307185

在hosts文件最后添加如下配置

192.168.88.132	www.123.com		#Linux 主机ip		本机配置的域名

image-20200703112615732

浏览器地址栏输入 www.123.com:8080,出现如下界面:

image-20200703112723058

​ 配置完成之后,我们便可以通过 www.123.com:8080 访问到第一步出现的 Tomcat 初始界面。那么如何只需要输入 www.123.com 便可以跳转到 Tomcat 初始界面呢?便用到 nginx的反向代理。

5.2 在 nginx 中进行请求转发配置(反向代理配置)

找到nginx 的配置文件 nginx.conf

[root@bogon bin]# cd /usr/local/nginx/
[root@bogon nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@bogon nginx]# cd conf/
[root@bogon conf]# ls
fastcgi.conf      fastcgi_params    koi-utf  mime.types  nginx.conf scgi_params       uwsgi_params      win-utf  fastcgi.conf.default  fastcgi_params.default  			   koi-win  mime.types.default  nginx.conf.default  scgi_params.default  	 uwsgi_params.default
[root@bogon conf]# vi nginx.conf

在 nginx.conf 配置文件中增加如下配置:

    server {
    
    
        listen       80;
        server_name  192.168.88.132;	#nginx访问地址

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
    
    
            root   html;
            proxy_pass http://192.168.88.132:8080;	#转发到目标地址
            index  index.html index.htm;
        }

        #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;
        }

image-20200703113737408

​ 如上配置,我们监听 80 端口,访问域名为 www.123.com,不加端口号时默认为 80 端口,故访问该域名时会跳转到 192.168.88.132:8080 路径上。

5.3 启动nginx测试

在浏览器端输入 www.123.com 结果如下:

注意:修改完nginx.conf 配置文件后,启动nginx 重新加载一下配置文件 ./nginx -s reload

image-20200703115255357

反向代理成功!

反向代理实例二

实现效果:使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中

nginx 监听端口为 9001,

访问 http://127.0.0.1:9001/edu/ 直接跳转到 127.0.0.1:8081

访问 http://127.0.0.1:9001/vod/ 直接跳转到 127.0.0.1:8082

反向代理配置步骤

1. 准备两个 tomcat

​ 在usr/src 下建立两个文件夹 tomcat8081 tomcat8082,并在这两个文件夹下放入两个tomcat ,并解压。

创建文件夹命令:mkdir tomcat8081,mkdir tomcat8082

解压命令:tar -xvf apache-tomcat-7.0.70.tar.gz

image-20200703132442979

先查看本机的tomcat是否正在运行:ps -ef|grep tomcat,如果正在运行根据运行的进程id号杀死正在运行的tomcat进程 kill 进程id号:

image-20200703132915667

修改两个tomcat的端口号:一个 8081 端口,一个 8082 端口。

进入tomcat 的conf文件夹下,并vi 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
 -->
<!-- 为避免冲突从8005改为8025 -->
<Server port="8025" 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
    -->
    <!-- 为避免冲突从8080改为8081 -->
    <Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- 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 -->
   <!-- 为避免冲突从8009改为8029 -->
    <Connector port="8029" 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>

修改完成后,到bin目录下 ./startup.sh 运行8082端口的tomcat

同理8082端口的tomcat 同样如上配置并运行启动!

image-20200703150717158

2.为两个tomcat 添加页面

向两个tomcat服务器的webapps下分别创建edu 和 文件夹,并将a.html 和 b.html 分别放入这两个文件夹。(注:a.html 和 b.html 自己随便建立一个,里面输入自己想展示的信息,能够区分是来自不同tomcat 服务器即可)

image-20200703150959414

image-20200703151009398

image-20200703151139117

image-20200703151154862

测试访问:

image-20200703151234484

image-20200703151305402

3. 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  192.168.88.132;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
    
    
            root   html;
            proxy_pass http://127.0.0.1:8080;
            index  index.html index.htm;
        }

        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
    
    
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
    
    
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    # 在这里把注释去掉,添加一个server 端口监听9001
    server {
    
    
        listen       9001;
        server_name  192.168.88.132;
	# 在下面 配置转发到不同的tomcat 中的内容 格式:~ /项目名/
        location ~ /edu/ {
    
    
			proxy_pass http://127.0.0.1:8001;
        }
        
        location ~ /vod/ {
    
    
			proxy_pass http://127.0.0.1:8002;
        }
    }


    # HTTPS server
    #
    #server {
    
    
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

image-20200703152200451

配置完成后,开放对外访问的端口号,如果防火墙已经关闭就不用了。

在/nginx/sbin/中执行 ./nginx -s reload 重新加载配置文件。

4. 测试

image-20200703162254139

5. location 指令说明

该指令用于匹配 URL。
语法如下:

  1. = :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配
    成功,就停止继续向下搜索并立即处理该请求。
  2. ~:用于表示 uri 包含正则表达式,并且区分大小写。
  3. ~*:用于表示 uri 包含正则表达式,并且不区分大小写。
  4. ^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。

注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。

nginx 配置实例-负载均衡

1、实现效果

​ 浏览器地址栏输入地址http://192.168.17.129/edu/a.html,负载均衡效果,平均到80828081 端口中。

2、准备工作

准备两 tomcat 服务器,一台 8082,一台 8081

在两台 tomcat 里面 webapps 目录中,创建名称是 edu 文件夹,在edu 文件夹中创建页面 a.html,用于测试。

3. 在 nginx 的配置文件中进行负载均衡的配置

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;
    
    # 加上upstream 
    upstream myserver {
    
    
        server  192.168.88.132:8080; #参与负载均衡的服务器地址1
        server  192.168.88.132:8081; #参与负载均衡的服务器地址2
    }

        server {
    
    
        listen       80;
        server_name  192.168.88.132;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
    
    
        	# 加上代理规则
            proxy_pass http://myserver;
            
            root   html;
            index  index.html index.htm;
        }

        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
    
    
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
    
    
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
 }


    # another virtual host using mix of IP-, name-, and port-based configuration
    
    # HTTPS server
    #
    #server {
    
    
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

4.访问测试

访问http://192.168.88.132/edu/a.html:第一次访问显示如下:

image-20200703172329625

刷新页面,效果如下:

image-20200703172344191

可以看出,访问该页面的时候,nginx会把请求平均分担到8080和8081两个服务器。

5.nginx分配服务器策略

第一种 轮询策略(默认)

​ 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。

第二种 权重策略 weight

​ weight 代表权重默认为 1,权重越高被分配的客户端越多。

#例如:
    upstream myserver {
    
    
        server  192.168.88.132:8080 weight=5; #参与负载均衡的服务器地址1
        server  192.168.88.132:8081 weight=10; #参与负载均衡的服务器地址2
    }
# 如上,8080的权重为5 8081权重为10,则nginx 负载均衡分配时,分配的8081比例更大

第三种 ip哈希策略 ip_hash

​ 每个请求按访问 ip 的hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决session问题。

#例如:
    upstream myserver {
    
    
    	ip_hash
        server  192.168.88.132:8080; #参与负载均衡的服务器地址1
        server  192.168.88.132:8081; #参与负载均衡的服务器地址2
    }
# 如上,每个请求按访问 ip 的hash 结果分配,即:某一个用户访问该服务器,根据该用户的ip地址分配一个ip_hash,并随机分配到端口为8080或者8081的服务器,该用户这个ip下次再访问服务器时,仍然默认访问上次分配的服务器,而不会再次随机分配。

第四种 fair(第三方):

​ 按后端服务器的响应时间来分配请求,响应时间短的优先分配。

#例如:
    upstream myserver {
    
    
        server  192.168.88.132:8080; #参与负载均衡的服务器地址1
        server  192.168.88.132:8081; #参与负载均衡的服务器地址2
        fair
    }
# 如上,访问该服务器时,通过判断 8080 或者 8081 服务器响应的时间,来进行分配访问,谁的响应时间短,优先访问谁。

Nginx配置实例-动静分离

1. 动静分离简述

​ Nginx 动静分离简单来说就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和静态页面物理分离。严格意义上说应该是动态请求跟静态请求分开,可以理解成使用 Nginx 处理静态页面Tomcat 处理动态页面。动静分离从目前实现角度来讲大致分为两种,一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案另外一种方法就是动态跟静态文件混合在一起发布,通过 nginx 来分开

​ 通过location 指定不同的后缀名实现不同的请求转发。通过 expires 参数设置,可以使浏览器缓存过期时间,减少与服务器之前的请求和流量。具体 Expires 定义:是给一个资源设定一个过期时间,也就是说无需去服务端验证,直接通过浏览器自身确认是否过期即可,所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,不建议使用 Expires 来缓存),我这里设置 3d,表示在这 3 天之内访问这个 URL,发送一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码304,如果有修改,则直接从服务器重新下载,返回状态码 200。

执行流程图

image-20200703174523520

2. 准备工作

liunx 系统中准备静态资源,用于进行访问:

首先在根路径下创建 staticresource 文件夹,并在其中建立 www 和 image文件夹用于存放静态资源:

image-20200703175539038

在www 文件夹中放置一个a.html 在 image 放置lf.jpg

image-20200703175727463

3. 具体配置

在nginx 配置文件中配置静态资源访问

配置内容如下:

#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  192.168.88.132;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        
		#配置静态资源访问
        location /www/ {
    
    
            root   /staticresource/;
            index  index.html index.htm;
        }

        location /image/{
    
    
            root /staticresource/;
            autoindex on;
        }
        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
    
    
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
    
    
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
 }

    # HTTPS server
    #
    #server {
    
    
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    
    
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

4. 测试查看效果

浏览器中输入地址

http://192.168.88.132/image/lf.jpg

image-20200703180641270

http://192.168.88.132/www/a.html

image-20200703180944677

image-20200703184404591

Nginx配置高可用的集群(了解)

什么是高可用

image-20200703185144421

1、需要的环境

(1)需要两台 nginx 服务器
(2)需要 keepalived
(3)需要虚拟 ip

2、配置高可用的准备工作
(1)需要两台服务器 192.168.17.129 和 192.168.17.131
(2)在两台服务器安装 nginx
(3)在两台服务器安装 keepalived

3、在两台服务器安装 keepalived
(1)使用 yum 命令进行安装
yum install keepalived –y

image-20200703185557792

(2)安装之后,在 etc 里面生成目录 keepalived,有文件 keepalived.conf

4、完成高可用配置(主从配置)
(1)修改/etc/keepalived/keepalivec.conf 配置文件

global_defs {
    
    
 notification_email {
    
    
 [email protected]
 [email protected]
 [email protected]
 }
 notification_email_from [email protected]
 smtp_server 192.168.17.129
 smtp_connect_timeout 30
 router_id LVS_DEVEL
}
vrrp_script chk_http_port {
    
    
 script "/usr/local/src/nginx_check.sh"
 interval 2 #(检测脚本执行的间隔)
 weight 2
}
vrrp_instance VI_1 {
    
    
 state BACKUP # 备份服务器上将 MASTER 改为 BACKUP 
 interface ens33 //网卡
 virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
 priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小
 advert_int 1
 authentication {
    
    
 auth_type PASS
 auth_pass 1111
 }
 virtual_ipaddress {
    
    
 192.168.17.50 // VRRP H 虚拟地址
 } 
 }

(2)在/usr/local/src 添加检测脚本

#!/bin/bash
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];then
 /usr/local/nginx/sbin/nginx
 sleep 2
 if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
 killall keepalived
 fi
fi

(3)把两台服务器上 nginx 和 keepalived 启动
启动 nginx:./nginx

​ 启动 keepalived:systemctl start keepalived.service

5、最终测试
(1)在浏览器地址栏输入 虚拟 ip 地址 192.168.17.50

image-20200703185611321

image-20200703185626463

(2)把主服务器(192.168.17.129)nginx 和 keepalived 停止,再输入 192.168.17.50

image-20200703185651965

Nginx的原理

1、mater 和 worker

image-20200703192429354

image-20200703192138820

2、worker如何进行工作的

image-20200703192444771

3、一个 master 和多个 woker 有好处

(1)可以使用 nginx –s reload 热部署,利用 nginx 进行热部署操作
(2)每个 woker 是独立的进程,如果有其中的一个 woker 出现问题,其他 woker 独立的,
继续进行争抢,实现请求过程,不会造成服务中断

4、设置多少个 woker 合适

worker 数和服务器的 cpu 数相等是最为适宜的。

5、连接数 worker_connection

第一个:发送请求,占用了 woker 的几个连接数?
答案:2 或者 4 个
第二个:nginx 有一个 master,有四个 woker,每个 woker 支持最大的连接数 1024,支持的最大并发数是多少?

  • 普通的静态访问最大并发数是: worker_connections * worker_processes /2。
  • 而如果是 HTTP 作 为反向代理来说,最大并发数量应该是 worker_connections *
    worker_processes/4。

猜你喜欢

转载自blog.csdn.net/weixin_43591980/article/details/107115961