一文帮你整理掌握Nginx(一)

简介: 一文帮你整理掌握Nginx
  • 第一章:Nginx概述
  • 第二章:Nginx单实例安装
  • 第三章:Nginx反向代理
  • 第四章:Nginx负载均衡

第一章:Nginx概述

1.1、Nginx概述

Nginx(“engine x”)是一个高性能的HTTP和反向代理服务器,特点是占有内存少,并发能力强,事实上Nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用Nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

1.2、Nginx官网

官网地址:http://nginx.org/

1.3、Nginx用处

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

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能。

项目地址:https://github.com/YunaiV/ruoyi-vue-pro

第二章:Nginx单实例安装

2.1、环境说明

模拟工具:VMware-workstation-full-15.5.6-16341506.exe

操作系统:CentOS-6.10-x86_64-bin-DVD1.iso、纯净安装、桌面版

内存大小:2GB

连接工具:SecureCRT

2.2、安装依赖

[root@caochenlei ~]# yum install -y gcc gcc-c++ make libtool wget pcre pcre-devel zlib zlib-devel openssl openssl-devel

2.3、Nginx下载

[root@caochenlei ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz

2.4、Nginx解压

[root@caochenlei ~]# tar -zxvf nginx-1.18.0.tar.gz

2.5、Nginx安装

[root@caochenlei ~]# cd nginx-1.18.0
[root@caochenlei nginx-1.18.0]# ./configure
[root@caochenlei nginx-1.18.0]# make && make install

注意:安装完成后的路径为:/usr/local/nginx

2.6、Nginx命令

普通启动服务:/usr/local/nginx/sbin/nginx

配置文件启动:/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

  • 暴力停止服务:/usr/local/nginx/sbin/nginx -s stop
  • 优雅停止服务:/usr/local/nginx/sbin/nginx -s quit
  • 检查配置文件:/usr/local/nginx/sbin/nginx -t
  • 重新加载配置:/usr/local/nginx/sbin/nginx -s reload
  • 查看相关进程:ps -ef | grep nginx

2.7、开放防火墙

[root@caochenlei ~]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
[root@caochenlei ~]# /etc/rc.d/init.d/iptables save
iptables:将防火墙规则保存到 /etc/sysconfig/iptables:[确定]

2.8、启动后效果

1.png

基于微服务的思想,构建在 B2C 电商场景下的项目实战。核心技术栈,是 Spring Boot + Dubbo 。未来,会重构成 Spring Cloud Alibaba 。

项目地址:https://github.com/YunaiV/onemall

第三章:Nginx反向代理

3.1、概述

Nginx不仅可以做反向代理,还能用作正向代理来进行上网等功能,正向代理:如果把局域网外的Internet想象成一个巨大的资源库,则局域网中的客户端要访问Internet,则需要通过代理服务器来访问,这种代理服务就称为正向代理。对于反向代理,客户端对代理是无感知的,因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器IP地址。

3.2、配置反向代理实例1

3.2.1、实现效果

打开浏览器,在浏览器地址栏输入地址:http://www.123.com,跳转到Liunx系统Tomcat主页面中。

2.png

3.2.2、实现思路

3.png

3.2.3、实现步骤

步骤一:修改Windows中的hosts域名映射

复制“C:\Windows\System32\drivers\etc\hosts”到桌面,右键记事本打开,在里边加上以下代码保存,然后再复制回去,不要直接修改,会不让保存!

#虚拟机域名       映射的网址
192.168.206.128 www.123.com

步骤二:修改Nginx中的配置文件并启动

[root@caochenlei ~]# vi /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  192.168.206.128;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass http:127.0.0.1:8080;
            root   html;
            index  index.html index.htm;
        }
[root@caochenlei ~]# /usr/local/nginx/sbin/nginx

步骤三:下载Tomcat、解压Tomcat、安装Tomcat、启动Tomcat

注意:Tomcat启动需要JDK,在这里我没有安装,使用系统自带的OpenJDK Runtime Environment (rhel-2.6.14.10.el6-x86_64 u181-b00)

下载:

[root@caochenlei ~]# wget https://mirror.bit.edu.cn/apache/tomcat/tomcat-7/v7.0.105/bin/apache-tomcat-7.0.105.tar.gz

解压:

[root@caochenlei ~]# tar -zxvf apache-tomcat-7.0.105.tar.gz

安装:

[root@caochenlei ~]# mv apache-tomcat-7.0.105 /usr/local/tomcat

启动:

[root@caochenlei ~]# /usr/local/tomcat/bin/startup.sh

添加到防火墙:

[root@caochenlei ~]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
[root@caochenlei ~]# /etc/rc.d/init.d/iptables save

如果关闭请用:

[root@caochenlei ~]# /usr/local/tomcat/bin/shutdown.sh

3.2.4、关闭服务

[root@caochenlei ~]# /usr/local/nginx/sbin/nginx -s quit
[root@caochenlei ~]# /usr/local/tomcat/bin/shutdown.sh

3.3、配置反向代理实例2

3.3.1、实现效果

使用Nginx反向代理,根据访问的路径跳转到不同端口的服务中。

4.png

3.3.2、实现思路

5.png

3.3.3、实现步骤

步骤一:修改Nginx的配置文件,然后启动

[root@caochenlei ~]# vi /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  192.168.206.128;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location ~ /edu/ {
            proxy_pass http://127.0.0.1:8080;
        }
        location ~ /vod/ {
            proxy_pass http://127.0.0.1:8081;
        }
[root@caochenlei ~]# /usr/local/nginx/sbin/nginx

步骤二:拷贝两个Tomcat,将其中一个的端口信息修改为8081,开启防火墙,然后分别启动这两台Tomcat

解压:

[root@caochenlei ~]# tar -zxvf apache-tomcat-7.0.105.tar.gz
[root@caochenlei ~]# mv apache-tomcat-7.0.105 /usr/local/tomcat1
[root@caochenlei ~]# tar -zxvf apache-tomcat-7.0.105.tar.gz
[root@caochenlei ~]# mv apache-tomcat-7.0.105 /usr/local/tomcat2

删除:

[root@caochenlei ~]# rm -f /usr/local/tomcat2/conf/server.xml

添加:

[root@caochenlei ~]# vi /usr/local/tomcat2/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="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" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">
    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->
    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8444" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8444" />
    -->
    <!-- Define an 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="8444" 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 -->
    <!--
    <Connector protocol="AJP/1.3"
               address="::1"
               port="8010"
               redirectPort="8444" />
    -->
    <!-- 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>

开启Tomcat2的防火墙:

[root@caochenlei ~]# /sbin/iptables -I INPUT -p tcp --dport 8081 -j ACCEPT
[root@caochenlei ~]# /etc/rc.d/init.d/iptables save

在每一个Tomcat的WebApps中创建一个文件夹和一个a.html文件:

[root@caochenlei ~]# mkdir -p /usr/local/tomcat1/webapps/edu
[root@caochenlei ~]# echo "<h1>This is 8080 Port</h1>" > /usr/local/tomcat1/webapps/edu/a.html
[root@caochenlei ~]# mkdir -p /usr/local/tomcat2/webapps/vod
[root@caochenlei ~]# echo "<h1>This is 8081 Port</h1>" > /usr/local/tomcat2/webapps/vod/a.html

启动:

[root@caochenlei ~]# /usr/local/tomcat1/bin/startup.sh
[root@caochenlei ~]# /usr/local/tomcat2/bin/startup.sh

步骤三:打开本机浏览器进行测试

在浏览器输入:http://192.168.206.128/edu/a.html

6.png

在浏览器输入:http://192.168.206.128/vod/a.html

7.png

3.3.4、关闭服务

[root@caochenlei ~]# /usr/local/nginx/sbin/nginx -s quit[root@caochenlei ~]# /usr/local/tomcat1/bin/shutdown.sh[root@caochenlei ~]# /usr/local/tomcat2/bin/shutdown.sh

3.4、location指令说明

描述:该指令用于匹配URL。

语法:

8.png

通配符:

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

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

第四章:Nginx负载均衡

4.1、概述

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

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

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

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

9.png

4.2、实现效果

浏览器地址栏输入地址:http://192.168.206.128/edu/a.html,负载均衡效果,将请求平均到8080和8081端口中。

10.png

4.3、实现思路

11.png

4.4、实现步骤

第一步:修改Nginx的配置文件

[root@caochenlei ~]# vi /usr/local/nginx/conf/nginx.conf
upstream myserver {
        server 192.168.206.128:8080;
        server 192.168.206.128:8081;
    }
    server {
        listen       80;
        server_name  192.168.206.128;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass http://myserver;
        }
[root@caochenlei ~]# /usr/local/nginx/sbin/nginx

第二步:在Tomcat2的webapps文件夹中,创建一个edu文件夹,在里边创建a.html

创建:

[root@caochenlei ~]# mkdir -p /usr/local/tomcat2/webapps/edu
[root@caochenlei ~]# echo "<h1>This is 8081 Port</h1>" > /usr/local/tomcat2/webapps/edu/a.html

启动:

[root@caochenlei ~]# /usr/local/tomcat1/bin/startup.sh
[root@caochenlei ~]# /usr/local/tomcat2/bin/startup.sh

第三步:测试效果

打开IE浏览器输入:http://192.168.206.128/edu/a.html

12.png

打开IE浏览器输入:http://192.168.206.128/edu/a.html

13.png

4.5、关闭服务

[root@caochenlei ~]# /usr/local/nginx/sbin/nginx -s quit[root@caochenlei ~]# /usr/local/tomcat1/bin/shutdown.sh[root@caochenlei ~]# /usr/local/tomcat2/bin/shutdown.sh

4.6、分配策略

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

14.png

weight:weight代表权重,默认为1,权重越高被分配的客户端越多,weight和访问比率成正比,用于后端服务器性能不均的情况。例如:

15.pngip_hash:每个请求按访问IP的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。例如:

16.png

fair(第三方):按后端服务器的响应时间来分配请求,响应时间短的优先分配。例如:

17.png

相关文章
|
运维 文件存储 数据安全/隐私保护
揭秘!真假美猴王与如来的那起运维事故
这场“真假美猴王”的恶作剧的起因是什么,是猴性的扭曲还是道德的沦丧,取经项目组又遭遇了怎样的至暗时刻?今天,我们就来聊一聊。
58241 1
揭秘!真假美猴王与如来的那起运维事故
|
6天前
|
云安全 人工智能 运维
阿里云联动百位企业安全专家,共识Agent防御最佳实践
当Agent成为新员工,你的安全边界在哪里?
1908 6
阿里云联动百位企业安全专家,共识Agent防御最佳实践
|
4天前
|
存储 人工智能 关系型数据库
阿里云AI产品与云产品最新组合套餐:Token Plan、AI coding及云服务器和建站等组合优惠价
阿里云推出全新“算力+模型+应用”一站式云与AI组合套餐活动,覆盖从个人开发者到中大型企业的全场景需求。核心亮点为分三档定价的Token Plan订阅服务,支持Qwen3.8-Max-Preview大模型调用,错峰时段最低可享0.2折优惠。活动同步推出AI Coding、智能体部署、云电脑托管、0代码建站等十余类场景化组合,搭配99元/年的普惠云服务器、88元/年的入门数据库等经典特惠产品,还为企业提供1V1定制化AI转型方案,大幅降低了不同用户群体拥抱AI的技术门槛与采购成本。
640 110
|
14天前
|
人工智能 JSON 安全
Fastjson远程代码执行漏洞,阿里云AI安全为您保驾护航
阿里云AI安全产品联动防御Fastjson攻击
2524 13
Fastjson远程代码执行漏洞,阿里云AI安全为您保驾护航
|
14天前
|
人工智能 自然语言处理 数据挖掘
Qwen3.8-Max-Preview深度全解析:2.4万亿参数旗舰MoE模型+Token Plan限时优惠完整落地指南
2026年7月,全新旗舰级混合专家大模型Qwen3.8-Max-Preview正式开放抢先体验,作为通义千问Qwen3系列规格最高、综合推理能力顶尖的新一代模型,该模型总参数量达到2.4万亿(2.4T),是当前线上可调用的原生多模态旗舰模型,综合推理水准对标海外顶级Fable 5模型,在复杂工程开发、长文档深度分析、多步骤智能体自治、跨境多语言创作、海量数据挖掘五大高难度业务场景实现跨越式性能提升。
1379 2
|
12天前
|
人工智能 前端开发 Linux
Codex 桌面版安装 + CC Switch 接入第三方 API 完整教程(2026 最新)
2026最新教程:手把手教你安装Codex桌面版,通过CC Switch v3.17.0一键接入Fenno等国产API(兼容OpenAI Responses格式),跳过账号登录,完整启用代码审查、多步任务与上下文感知功能。零基础友好,全程图文实操。(239字)
1299 2
|
16天前
|
人工智能
Qwen3.8抢先体验!正式版即将发布并开源!
千问Qwen3.8即将开源,参数达2.4T,进化速度以“天”计,实力媲美Fable 5。预览版Qwen3.8-Max已上线阿里Token Plan等平台,限时优惠:日间Credits低至1折,夜间更优,个人/团队版月付仅35元起!
1415 54
|
12天前
|
自然语言处理 测试技术 API
通义千问Qwen3.8-Max-Preview全功能解析:2.4万亿参数旗舰模型深度使用指南
在大模型技术持续迭代的当下,通义千问推出的Qwen3.8-Max-Preview作为新一代旗舰预览版模型,凭借2.4万亿参数的超大规模、多模态融合能力与全场景适配特性,成为开发者与企业用户探索AI应用的核心工具。该模型采用稀疏混合专家(MoE)架构,是通义千问首个突破万亿参数的多模态模型,可同时处理文本、图像、视频与文档等多种数据形态,在全栈代码开发、复杂逻辑推理、长文档分析与多智能体协作等场景实现跨越式升级。本文将全面拆解Qwen3.8-Max-Preview的核心功能,详解API调用流程与配置方法,覆盖多场景实战技巧,帮助用户快速掌握这款旗舰模型的使用方法,充分释放其性能潜力。
667 2