Linux之Nignx及负载均衡&动静分离

简介: Linux之Nignx及负载均衡&动静分离




前言

      在上一期的博客中我与各位老铁带来了有关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)或者与后端服务(如数据库、缓存服务器)进行交互,提供高性能的动态内容服务。
内容分发网络(CDN) Nginx可以与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的端口号

新建服务器

修改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的请求修改对应的端口号的域名即可。

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

相关实践学习
部署高可用架构
本场景主要介绍如何使用云服务器ECS、负载均衡SLB、云数据库RDS和数据传输服务产品来部署多可用区高可用架构。
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
目录
相关文章
|
3月前
|
负载均衡 安全 前端开发
百度搜索:蓝易云【Nginx与Tomcat负载均衡-动静分离教程】
这些是将Nginx与Tomcat结合使用实现负载均衡和动静分离的基本步骤。根据您的需求和具体环境,可能还需要进行其他配置和调整。请确保在进行任何与网络连接和安全相关的操作之前,详细了解您的网络环境和安全需求,并采取适当的安全措施。
49 1
|
4月前
|
负载均衡 前端开发 应用服务中间件
【Linux】Nginx安装使用负载均衡及动静分离(前后端项目部署),前端项目打包
【Linux】Nginx安装使用负载均衡及动静分离(前后端项目部署),前端项目打包
381 0
|
18天前
|
负载均衡 Java 关系型数据库
linux 下amoeba实现数据库的负载均衡
linux 下amoeba实现数据库的负载均衡
13 1
|
3月前
|
负载均衡 算法 前端开发
Ngnix之反向代理、负载均衡、动静分离
Nginx是一个高性能的开源Web服务器,它还可以用作反向代理、负载均衡器以及动静分离的工具。
|
4月前
|
负载均衡 前端开发 应用服务中间件
百度搜索:蓝易云【Nginx使用之反向代理、负载均衡、动静分离教程。】
通过这样的配置,Nginx将根据请求的URL路径选择是将请求转发到后端服务器还是直接返回静态资源文件。
139 0
|
4月前
|
负载均衡 应用服务中间件 Linux
Nginx安装Windows、Linux | 正向代理、反向代理、负载均衡
Nginx安装Windows、Linux | 正向代理、反向代理、负载均衡
96 0
|
6天前
|
机器学习/深度学习 缓存 监控
linux查看CPU、内存、网络、磁盘IO命令
`Linux`系统中,使用`top`命令查看CPU状态,要查看CPU详细信息,可利用`cat /proc/cpuinfo`相关命令。`free`命令用于查看内存使用情况。网络相关命令包括`ifconfig`(查看网卡状态)、`ifdown/ifup`(禁用/启用网卡)、`netstat`(列出网络连接,如`-tuln`组合)以及`nslookup`、`ping`、`telnet`、`traceroute`等。磁盘IO方面,`iostat`(如`-k -p ALL`)显示磁盘IO统计,`iotop`(如`-o -d 1`)则用于查看磁盘IO瓶颈。
|
3天前
|
监控 Linux Windows
50个必知的Linux命令技巧,你都掌握了吗?(下)
50个必知的Linux命令技巧,你都掌握了吗?(下)
|
3天前
|
Linux Shell Windows
Linux 常用基本命令
Linux 常用基本命令