Linux之Nignx及负载均衡&动静分离-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

 


欢迎来到我的CSDN主页

我是君易--鑨一个在CSDN分享笔记的博主。

推荐给大家我的博客专栏《LInux实战开发》。

如果感觉还不错的话请给我关注加三连吧

期待你的加入一起学习一起进步

前言

        在上一期的博客中我与各位老铁带来了有关Linux系统安装配置项目环境内容有jdk、tomcat服务器、mysql数据库等等以及如何去部署我们的会议OA项目和前后端分离项目的后端接口最后还和大家分享了该如何去使用两个不同的端口号去访问不同的项目。今天的这期博客基于上期的博客完成前后端项目的部署以及Nignx的知识了解及使用。


一、Nignx的简介

1. 基本概述

        Nginx发音为"engine x"是一个开源的高性能Web服务器反向代理服务器。它具有轻量级和高并发处理能力被广泛用于构建高性能的网站和应用程序。

        Nginx通常用作HTTP服务器可以处理静态文件、索引文件和自动索引。它也可以作为反向代理服务器用于负载均衡、HTTP缓存、访问控制和安全防护等功能。

        与传统的Web服务器相比Nginx的设计重点在于高并发连接的处理能力以及低内存使用和高响应速度。这使得Nginx成为处理大量并发请求的理想选择特别适合用于性能要求较高的网站和应用程序。

        Nginx还支持各种功能扩展和模块化可以通过第三方模块来实现额外的功能如HTTP缓存、SSL/TLS加密、反向代理、日志处理等。这种灵活性使得Nginx广泛应用于不同的场景包括高负载的网站、内容分发网络CDN、应用程序服务器和微服务架构等。

2.  Nignx的应用场景

常见的应用场景
应用场景说明
静态文件服务Nginx能够高效地提供静态文件如HTML、CSS、JavaScript、图像等的传输适用于搭建文件服务器或静态网站。
反向代理服务器Nginx经常被用作反向代理服务器将客户端请求转发给后端的应用服务器处理。它可以实现负载均衡、缓存静态内容、提供SSL/TLS加密等功能提升服务性能和安全性。
负载均衡Nginx作为负载均衡器可以将客户端请求分发到多个后端服务器平均分担服务器负载提高系统的可用性和可扩展性。
后端应用服务器Nginx可以作为应用服务器处理动态请求如PHP、Node.js或者与后端服务如数据库、缓存服务器进行交互提供高性能的动态内容服务。
内容分发网络CDNNginx可以与CDN配合使用加速静态内容的分发降低带宽压力提高用户访问速度。
WebSocket应用Nginx可以代理和负载均衡WebSocket请求适用于实时通信和即时通讯应用。
安全防护Nginx具备一些安全防护功能如反爬虫限制、请求频率限制、黑白名单过滤等可以增强Web应用的安全性。

        Nginx实际上非常灵活可以根据需求进行定制配置和扩展。无论是中小型网站、高流量网站还是复杂的微服务架构Nginx都是一个强大的工具

 3. 代理服务器的原理

        Nginx代理服务器的原理主要是基于反向代理。反向代理服务器位于客户端和目标服务器之间代替目标服务器接收客户端的请求并向目标服务器转发请求从而使得客户端能够访问目标服务器的资源。

        具体来说当客户端发送一个HTTP请求到反向代理服务器时反向代理服务器会先解析这个请求然后根据请求中的目标地址和端口号将请求转发到目标服务器。目标服务器处理请求并返回响应给反向代理服务器反向代理服务器再将响应转发给客户端。在整个过程中客户端与反向代理服务器之间的通信是透明的客户端不需要知道目标服务器的存在。

        Nginx作为反向代理服务器可以配置多个监听地址和端口以便为不同的客户端提供代理服务。同时Nginx还支持负载均衡、安全防护等高级功能可以有效地提高系统的性能和安全性。

简易图解 

二、安装Nignx

        在之前的博客中我们已经将Nignx的安装包导入到了我们的文件夹中

 1. 下载Nignx所需的依赖

指令yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel

2. 解压安装包

指令tar -xvf nginx-1.13.7.tar.gz

解压之后会对应的生成一个文件夹

3.配置及安装Nignx

相关指令

  1. ./configure --with-http_stub_status_module --with-http_ssl_module  --->编译执行配置: 考虑到后续安装ssl证书 添加两个模块需要进到nignx的文件夹中运行
  2. make && make install    ---->安装Nignx  需要进到nignx的文件夹中运行

 配置

 安装

三、Nignx的使用

1. 基础使用

        启动Nignx服务需要我们进入到nignx安装好的 /usr/local/nginx/sbin目录下输入相关的指令。

指令

  1. ./nginx    ------>启动
  2. ./nginx -s reload      -------->重新启动
  3. ./nginx -s stop      --------->关闭
  4. ./nginx -c /usr/local/nginx/conf/nginx.conf    ------->或者指定配置文件启动

2. 其他指令的使用

2.1 验证Nignx是否启动

        首先我们先要安装lsof的相关指令文件方便我们后续调用使用。

指令

  1. yum install -y lsof    ----->下载lsof指令文件

        当我们下载完lsof后我们在输入指定的指令去检验是否运行Nginx

指令lsof -i:80    ---->查看Nginx的当前状态

         此时我们的主机网页时访问不到我们的Nginx因为在防火墙那我们并没有去开设一个端口供我们的Nginx去使用因此区开设一个防火墙端口号。

指令

  1.  firewall-cmd --zone=public --add-port=80/tcp --permanent   ---->开设端口号
  2. firewall-cmd --reload && firewall-cmd --list-port ----->刷新并查看防火墙状态和端口信息
  3. systemctl start nginx.service   ---->设置开机自启动Nignx
  4. systemctl enable nginx.service  ----->设置开机不自启动Nignx

        然后再在我们主机的网页去访问Nignx。 以下是访问成功的案例

2.2 实现负载均衡

图示

        实现负载均衡首先我们要在创建一个文件夹存放tomcat服务器或者赋值一个原有的tomcat服务器文件夹取一个别名将复制后的文件中的项目文件删除掉保证是一个全新的服务器。然后还要在防火墙开设一个端口提供给新服务器使用访问。我采取的是重新导入一个新的tomcat安装包进行解压        

        首先将压缩包进行压缩配置。

涉及指令

  1.  tar -xvf apache-tomcat-8.5.20-nignx.tar.gz  ----->解压压缩包
  2. 整理服务器的内容修改server.xml的端口号

  3.  

 新建服务器

 修改server.xml中的端口号

        在server.xml文件中修改端口号每一个端口号都修改一下防止重复。

 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="8006" 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" />
  <!-- 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
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <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/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8010" 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>

 开设防火墙端口并主机成功访问

四、Nginx配置

        在nginx文件下conf文件的nginx.conf中进行配置将下述代码添加到文件里面

#服务器的集群
    upstream  tomcat_list {  #服务器集群名字
        server    127.0.0.1:8080  weight=1;   #服务器1   weight是权重的意思权重越大分配的概率越大。
        server    172.17.0.4:8080  weight=2; #服务器2   weight是权重的意思权重越大分配的概率越大
    } 

         配置完Nginx的nginx.conf文件后需要重新启动Nginx服务方可生效。

指令./nginx -s reload ------>重启Nginx服务

五、 前端部署

1. 准备工作

前端项目打包之前需要增加以下的设置

在前端项目中 config文件下的index.js中要增加以下代码 : 

 assetsPublicPath: './',//修改后

如图: 

在前端项目中 build文件下的 utils.js 中增加以下代码 : 


 // 解决icon路径加载错误
        publicPath:'../../'

如图: 

在前端项目的跟目录中cmd打开命令窗口

输入命令 : npm run build   ( 进行前端项目打包 )

如图 : 

2.部署

在 /usr/local/ 目录下创建一个文件夹为mypor 并且进入文件夹之后将dist文件拖入mypor文件夹中因为我们的项目文件的的后缀名为.zip所以不能为使用tar进行解压需要下载unzip进行项目解压

指令yum install -y unzip

将该文件进行解压 

输入命令 : unzip dist.zip然后在配置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  tomcat_list {  #服务器集群名字
        server    127.0.0.1:8080  weight=1;   #服务器1   weight是权重的意思权重越大分配的概率越大。
        #server    172.17.0.4:8080  weight=2; #服务器2   weight是权重的意思权重越大分配的概率越大
    } 

    server {
        listen       80;            #监听80端口可以改成其他端口
        #server_name  localhost;    #当前服务的域名
	server_name  www.zking.com; #当前服务的域名(虚拟域名也可以)
	root         html/crm;      #将要访问的网站的根目录nginx节点会自动继承父节点的配置

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

	location / {
	        #该句代码是为解决history路由不能跳转的问题在vue-router官网有介绍 
		try_files $uri $uri/  /index.html;
	}
	location  ^~/api/ {
		#^~/api/表示匹配前缀是api的请求proxy_pass的结尾有/ 则会把/api/*后面的路径直接拼接到后面即移除api
		proxy_pass http://tomcat_list/;
	}
        #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;
    #    }
    #}

}

输入命令  cd /usr/local/nginx/sbin/  进入到文件目录下然后输入命令 ./nginx -s reload   重启nginx服务在将后端的war包 传入tomcat服务器中。并且输入命令 :   ./startup.sh    开启访问

 

在浏览器中进行访问 使用虚拟机的IP加tomcat的端口进行访问项目

 

 这里会考虑到网址域名的问题需要在到文件资源管理器中进入到 以下本地目录

C:\Windows\System32\drivers\etc找到 hosts 文件进行修改IP的请求修改对应的端口号的域名即可。

本期的博客分享到此结束三连加关注支持博客一下呗 

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: linux