天天看點

一文幫你整理掌握Nginx

點選上方“芋道源碼”,選擇“設為星标”

管她前浪,還是後浪?

能浪的浪,才是好浪!

每天 10:33 更新文章,每天掉億點點頭發...

源碼精品專欄

  • 原創 | Java 2021 超神之路,很肝~
  • 中文詳細注釋的開源項目
  • RPC 架構 Dubbo 源碼解析
  • 網絡應用架構 Netty 源碼解析
  • 消息中間件 RocketMQ 源碼解析
  • 資料庫中間件 Sharding-JDBC 和 MyCAT 源碼解析
  • 作業排程中間件 Elastic-Job 源碼解析
  • 分布式事務中間件 TCC-Transaction 源碼解析
  • Eureka 和 Hystrix 源碼解析
  • Java 并發源碼

來源:blog.csdn.net/qq_38490457/

article/details/108300342

  • 第一章:Nginx概述
  • 第二章:Nginx單執行個體安裝
  • 第三章:Nginx反向代理
  • 第四章: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、安裝依賴

[[email protected] ~]# yum install -y gcc gcc-c++ make libtool wget pcre pcre-devel zlib zlib-devel openssl openssl-devel
           

2.3、Nginx下載下傳

[[email protected] ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
           

2.4、Nginx解壓

[[email protected] ~]# tar -zxvf nginx-1.18.0.tar.gz
           

2.5、Nginx安裝

[[email protected] ~]# cd nginx-1.18.0
[[email protected] nginx-1.18.0]# ./configure
[[email protected] 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、開放防火牆

[[email protected] ~]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
[[email protected] ~]# /etc/rc.d/init.d/iptables save
iptables:将防火牆規則儲存到 /etc/sysconfig/iptables:[确定]
           

2.8、啟動後效果

一文幫你整理掌握Nginx

基于微服務的思想,建構在 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首頁面中。

一文幫你整理掌握Nginx

3.2.2、實作思路

一文幫你整理掌握Nginx

3.2.3、實作步驟

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

複制“C:\Windows\System32\drivers\etc\hosts”到桌面,右鍵記事本打開,在裡邊加上以下代碼儲存,然後再複制回去,不要直接修改,會不讓儲存!

#虛拟機域名       映射的網址
192.168.206.128 www.123.com
           

步驟二:修改Nginx中的配置檔案并啟動

[[email protected] ~]# 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;
        }
[[email protected] ~]# /usr/local/nginx/sbin/nginx
           

步驟三:下載下傳Tomcat、解壓Tomcat、安裝Tomcat、啟動Tomcat

注意:Tomcat啟動需要JDK,在這裡我沒有安裝,使用系統自帶的OpenJDK Runtime Environment (rhel-2.6.14.10.el6-x86_64 u181-b00)

下載下傳:

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

解壓:

[[email protected] ~]# tar -zxvf apache-tomcat-7.0.105.tar.gz
           

安裝:

[[email protected] ~]# mv apache-tomcat-7.0.105 /usr/local/tomcat
           

啟動:

[[email protected] ~]# /usr/local/tomcat/bin/startup.sh
           

添加到防火牆:

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

如果關閉請用:

[[email protected] ~]# /usr/local/tomcat/bin/shutdown.sh
           

3.2.4、關閉服務

[[email protected] ~]# /usr/local/nginx/sbin/nginx -s quit
[[email protected] ~]# /usr/local/tomcat/bin/shutdown.sh
           

3.3、配置反向代理執行個體2

3.3.1、實作效果

使用Nginx反向代理,根據通路的路徑跳轉到不同端口的服務中。

一文幫你整理掌握Nginx

3.3.2、實作思路

一文幫你整理掌握Nginx

3.3.3、實作步驟

步驟一:修改Nginx的配置檔案,然後啟動

[[email protected] ~]# 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;
        }
[[email protected] ~]# /usr/local/nginx/sbin/nginx
           

步驟二:拷貝兩個Tomcat,将其中一個的端口資訊修改為8081,開啟防火牆,然後分别啟動這兩台Tomcat

解壓:

[[email protected] ~]# tar -zxvf apache-tomcat-7.0.105.tar.gz
[[email protected] ~]# mv apache-tomcat-7.0.105 /usr/local/tomcat1

[[email protected] ~]# tar -zxvf apache-tomcat-7.0.105.tar.gz
[[email protected] ~]# mv apache-tomcat-7.0.105 /usr/local/tomcat2
           

删除:

[[email protected] ~]# rm -f /usr/local/tomcat2/conf/server.xml
           

添加:

[[email protected] ~]# 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的防火牆:

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

在每一個Tomcat的WebApps中建立一個檔案夾和一個a.html檔案:

[[email protected] ~]# mkdir -p /usr/local/tomcat1/webapps/edu
[[email protected] ~]# echo "<h1>This is 8080 Port</h1>" > /usr/local/tomcat1/webapps/edu/a.html

[[email protected] ~]# mkdir -p /usr/local/tomcat2/webapps/vod
[[email protected] ~]# echo "<h1>This is 8081 Port</h1>" > /usr/local/tomcat2/webapps/vod/a.html
           

啟動:

[[email protected] ~]# /usr/local/tomcat1/bin/startup.sh
[[email protected] ~]# /usr/local/tomcat2/bin/startup.sh
           

步驟三:打開本機浏覽器進行測試

在浏覽器輸入:http://192.168.206.128/edu/a.html

一文幫你整理掌握Nginx

在浏覽器輸入:http://192.168.206.128/vod/a.html

一文幫你整理掌握Nginx

3.3.4、關閉服務

[[email protected] ~]# /usr/local/nginx/sbin/nginx -s quit[[email protected] ~]# /usr/local/tomcat1/bin/shutdown.sh[[email protected] ~]# /usr/local/tomcat2/bin/shutdown.sh

3.4、location指令說明

描述:該指令用于比對URL。

文法:

一文幫你整理掌握Nginx

通配符:

  • =:用于不含正規表達式的uri前,要求請求字元串與uri嚴格比對,如果比對成功,就停止繼續向下搜尋并立即處理該請求。
  • ~:用于表示uri包含正規表達式,并且區分大小寫。
  • ~*:用于表示uri包含正規表達式,并且不區分大小寫。
  • ^~:用于不含正規表達式的uri前,要求Nginx伺服器找到辨別uri和請求字元串比對度最高的location後,立即使用此location處理請求,而不再使用location塊中的正則uri和請求字元串做比對。

注意:如果uri包含正規表達式,則必須要有~或者~*辨別。

第四章:Nginx負載均衡

4.1、概述

用戶端發送多個請求到伺服器,伺服器處理請求,有一些可能要與資料庫進行互動,伺服器處理完畢後,再将結果傳回給用戶端。

這種架構模式對于早期的系統相對單一,并發請求相對較少的情況下是比較适合的,成本也低。但是随着資訊數量的不斷增長,通路量和資料量的飛速增長,以及系統業務的複雜度增加,這種架構會造成伺服器相應用戶端的請求日益緩慢,并發量特别大的時候,還容易造成伺服器直接崩潰。很明顯這是由于伺服器性能的瓶頸造成的問題,那麼如何解決這種情況呢?

我們首先想到的可能是更新伺服器的配置,比如提高CPU執行頻率,加大記憶體等提高機器的實體性能來解決此問題,但是我們知道摩爾定律的日益失效,硬體的性能提升已經不能滿足日益提升的需求了。最明顯的一個例子,天貓雙十一當天,某個熱銷商品的瞬時通路量是極其龐大的,那麼類似上面的系統架構,将機器都增加到現有的頂級實體配置,都是不能夠滿足需求的。那麼怎麼辦呢?

上面的分析我們去掉了增加伺服器實體配置來解決問題的辦法,也就是說縱向解決問題的辦法行不通了,那麼橫向增加伺服器的數量呢?這時候叢集的概念産生了,單個伺服器解決不了,我們增加伺服器的數量,然後将請求分發到各個伺服器上,将原先請求集中到單個伺服器上的情況改為将請求分發到多個伺服器上,将負載分發到不同的伺服器,也就是我們所說的負載均衡。

一文幫你整理掌握Nginx

4.2、實作效果

浏覽器位址欄輸入位址:http://192.168.206.128/edu/a.html,負載均衡效果,将請求平均到8080和8081端口中。

一文幫你整理掌握Nginx

4.3、實作思路

一文幫你整理掌握Nginx

4.4、實作步驟

第一步:修改Nginx的配置檔案

[[email protected] ~]# 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;
        }
[[email protected] ~]# /usr/local/nginx/sbin/nginx
           

第二步:在Tomcat2的webapps檔案夾中,建立一個edu檔案夾,在裡邊建立a.html

建立:

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

啟動:

[[email protected] ~]# /usr/local/tomcat1/bin/startup.sh
[[email protected] ~]# /usr/local/tomcat2/bin/startup.sh
           

第三步:測試效果

打開IE浏覽器輸入:http://192.168.206.128/edu/a.html

一文幫你整理掌握Nginx

打開IE浏覽器輸入:http://192.168.206.128/edu/a.html

一文幫你整理掌握Nginx

4.5、關閉服務

[[email protected] ~]# /usr/local/nginx/sbin/nginx -s quit[[email protected] ~]# /usr/local/tomcat1/bin/shutdown.sh[[email protected] ~]# /usr/local/tomcat2/bin/shutdown.sh

4.6、配置設定政策

輪詢(預設):每個請求按時間順序逐一配置設定到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。

一文幫你整理掌握Nginx

weight:weight代表權重,預設為1,權重越高被配置設定的用戶端越多,weight和通路比率成正比,用于後端伺服器性能不均的情況。例如:

一文幫你整理掌握Nginx

ip_hash:每個請求按通路IP的hash結果配置設定,這樣每個訪客固定通路一個後端伺服器,可以解決session的問題。例如:

一文幫你整理掌握Nginx

fair(第三方):按後端伺服器的響應時間來配置設定請求,響應時間短的優先配置設定。例如:

一文幫你整理掌握Nginx

第五章:Nginx動靜分離

5.1、概述

Nginx動靜分離簡單來說就是把動态跟靜态請求分開,不能了解成隻是單純的把動态頁面和靜态頁面實體分離。嚴格意義上說應該是動态請求跟靜态請求分開,可以了解成使用Nginx處理靜态頁面,Tomcat處理動态頁面。動靜分離從目前實作角度來講大緻分為兩種,一種是純粹把靜态檔案獨立成單獨的域名,放在獨立的伺服器上,也是目前主流推崇的方案;另外一種方法就是動态跟靜态檔案混合在一起釋出,通過Nginx來分開。

5.2、實作效果

如果不設定動靜分離,預設會通過Nginx的反向代理去找Tomcat對應的資源,現在我們在根目錄下建立一個/data/www/檔案夾,裡邊放上靜态資源,比如一個html頁面,在8080的那台Tomcat的WebApps下也建立一個www目錄,同樣是放一個靜态資源,當輸入這個靜态資源的請求時,通路到的是/data/www中的資料。

一文幫你整理掌握Nginx

5.3、實作思路

一文幫你整理掌握Nginx

5.4、實作步驟

第一步:建立靜态資源檔案,為了對比,Tomcat中也放一個

[[email protected] ~]# mkdir -p /data/www/
[[email protected] ~]# mkdir -p /usr/local/tomcat/webapps/ROOT/www
[[email protected] ~]# echo "<h1>/data/www/a.html</h1>" > /data/www/a.html
[[email protected] ~]# echo "<h1>/usr/local/tomcat/webapps/ROOT/www/a.html</h1>" > /usr/local/tomcat/webapps/ROOT/www/a.html
           

第二步:修改Nginx的配置檔案

[[email protected] ~]# 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 /www/ {
            root /data/;
            index index.html index.htm;
        }
[[email protected] ~]# /usr/local/nginx/sbin/nginx
           

第三步:啟動Tomcat

[[email protected] ~]# /usr/local/tomcat/bin/startup.sh
           

第四步:啟動浏覽器進行測試

打開浏覽器輸入:http://192.168.206.128/www/a.html

一文幫你整理掌握Nginx

5.5、關閉服務

[[email protected] ~]# /usr/local/nginx/sbin/nginx -s quit
[[email protected] ~]# /usr/local/tomcat/bin/shutdown.sh
           

第六章:Nginx高可用叢集

6.1、概述

前邊我們學習了反向代理、負載均衡、動靜分離,但試想一下,如果Nginx挂掉了,那麼服務肯定就沒有了,有沒有一種解決方案,可以保證Nginx挂掉了,服務也可以照常使用,答案肯定是有的,這就是我們接下來要學習的高可用叢集,采用的是一主一備的模式,當主節點Nginx挂掉,備份伺服器Nginx立刻跟上,這樣就保證了服務的高可用性。

6.2、實作效果

當主節點Nginx挂掉以後,服務依然可以正常使用。

6.3、實作思路

一文幫你整理掌握Nginx

6.4、實作步驟

第一步:修改主

Kubernetes 是目前唯一被業界廣泛認可的 Docker 分布式解決方案。通過Kubernetes,我們可以輕裝上陣的開發與管理複雜的業務系統。Kubernetes 已經毫無疑問地成為容器領域當之無愧的事實标準。

節點上的Nginx的配置檔案

[[email protected] ~]# 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;
        }
[[email protected] ~]# /usr/local/nginx/sbin/nginx
           

第二步:啟動主節點上的兩台Tomcat

[[email protected] ~]# /usr/local/tomcat1/bin/startup.sh
[[email protected] ~]# /usr/local/tomcat2/bin/startup.sh
           

第三步:安裝主節點上的keepalived

安裝keepalived:

[[email protected] ~]# yum install -y keepalived
           

删除keepalived的配置檔案:

[[email protected] ~]# rm -f /etc/keepalived/keepalived.conf
           

新增keepalived的配置檔案:

[[email protected] ~]# vi /etc/keepalived/keepalived.conf
           

注意:一定要注意router_id、state、interface的值,我就在這裡踩坑了。

! Configuration File for keepalived

global_defs {
   notification_email {
     [email protected]
     [email protected]
     [email protected]
   }
   notification_email_from [email protected]
   #郵件伺服器通知位址(暫不配置,預設即可)
   smtp_server 192.168.200.1
   #郵件伺服器逾時時間(暫不配置,預設即可)
   smtp_connect_timeout 30
   #目前虛拟機的IP位址
   router_id 192.168.206.128
}

vrrp_script Monitor_Nginx {
 script "/etc/keepalived/nginx_check.sh"    #檢測腳本執行的路徑
 interval 2                                 #檢測腳本執行的間隔
 weight 2                                   #檢測腳本執行的權重
}

vrrp_instance VI_1 {
    state MASTER         #辨別這個機器是MASTER還是BACKUP
    interface eth0       #目前機器的網卡名稱  
    virtual_router_id 51 #虛拟路由的編号,主備必須一緻
    priority 100         #主、備機取不同的優先級,主機值較大,備份機值較小
    advert_int 1         #(VRRP Multicast廣播周期秒數)
    authentication {
        auth_type PASS   #(VRRP認證方式)
        auth_pass 1111   #(密碼)
    }
    track_script {
  Monitor_Nginx #(調用Nginx程序檢測腳本)
 }
    virtual_ipaddress {
        192.168.206.50  #虛拟IP位址
    }
}
           

新增keepalived的檢測腳本:

[[email protected] ~]# vi /etc/keepalived/nginx_check.sh
#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process" | grep -v grep )" == "" ]
 then
 killall keepalived
fi
           

啟動keepalived服務:

[[email protected] ~]# service keepalived start
           

第四步:準備一台全新的虛拟機,安裝Nginx和keepalived

啟動虛拟機:

一文幫你整理掌握Nginx

安裝Nginx依賴:

[[email protected] ~]# yum install -y gcc gcc-c++ make libtool wget pcre pcre-devel zlib zlib-devel openssl openssl-devel
           

下載下傳Nginx檔案:

[[email protected] ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
           

安裝Nginx程式:

[[email protected] ~]# tar -zxvf nginx-1.18.0.tar.gz
[[email protected] ~]# cd nginx-1.18.0
[[email protected] nginx-1.18.0]# ./configure
[[email protected] nginx-1.18.0]# make && make install
[[email protected] nginx-1.18.0]# cd ~
           

開放Nginx防火牆:

[[email protected] ~]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
[[email protected] ~]# /etc/rc.d/init.d/iptables save
iptables:将防火牆規則儲存到 /etc/sysconfig/iptables:     [确定]
           

修改Nginx的配置:

[[email protected] ~]# 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;
        }
           

啟動Nginx的服務:

[[email protected] ~]# /usr/local/nginx/sbin/nginx
           

安裝keepalived:

[[email protected] ~]# yum install -y keepalived
           

删除keepalived的配置檔案:

[[email protected] ~]# rm -f /etc/keepalived/keepalived.conf
           

新增keepalived的配置檔案:

[[email protected] ~]# vi /etc/keepalived/keepalived.conf
           

注意:一定要注意router_id、state、interface的值,我就在這裡踩坑了。

! Configuration File for keepalived

global_defs {
   notification_email {
     [email protected]
     [email protected]
     [email protected]
   }
   notification_email_from [email protected]
   #郵件伺服器通知位址(暫不配置,預設即可)
   smtp_server 192.168.200.1
   #郵件伺服器逾時時間(暫不配置,預設即可)
   smtp_connect_timeout 30
   #目前虛拟機的IP位址
   router_id 192.168.206.129
}

vrrp_script Monitor_Nginx {
 script "/etc/keepalived/nginx_check.sh"    #檢測腳本執行的路徑
 interval 2                                 #檢測腳本執行的間隔
 weight 2                                   #檢測腳本執行的權重
}

vrrp_instance VI_1 {
    state BACKUP         #辨別這個機器是MASTER還是BACKUP
    interface eth1       #目前機器的網卡名稱  
    virtual_router_id 51 #虛拟路由的編号,主備必須一緻
    priority 10          #主、備機取不同的優先級,主機值較大,備份機值較小
    advert_int 1         #(VRRP Multicast廣播周期秒數)
    authentication {
        auth_type PASS   #(VRRP認證方式)
        auth_pass 1111   #(密碼)
    }
    track_script {
  Monitor_Nginx    #(調用Nginx程序檢測腳本)
 }
    virtual_ipaddress {
        192.168.206.50   #虛拟IP位址
    }
}
           

新增keepalived的檢測腳本:

[[email protected] ~]# vi /etc/keepalived/nginx_check.sh
#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process" | grep -v grep )" == "" ]
 then
 killall keepalived
fi
           

啟動keepalived服務:

[[email protected] ~]# service keepalived start
           

第五步:測試兩個Nginx是否能正确的将請求分發到不同的Tomcat(負載均衡)

打開IE浏覽器輸入:http://192.168.206.128/edu/a.html

一文幫你整理掌握Nginx

按住F5多重新整理兩遍,看看會不會,将請求轉發到Tomcat2中去。

一文幫你整理掌握Nginx

打開IE浏覽器輸入:http://192.168.206.129/edu/a.html

一文幫你整理掌握Nginx

按住F5多重新整理兩遍,看看會不會,将請求轉發到Tomcat2中去。

一文幫你整理掌握Nginx

打開IE浏覽器輸入:http://192.168.206.50/edu/a.html,測試虛拟IP能不能實作負載均衡。

一文幫你整理掌握Nginx

按住F5多重新整理兩遍,看看會不會,将請求轉發到Tomcat2中去。

一文幫你整理掌握Nginx

經過測試,我們發現一主一從、虛拟IP都能正常的進行負載均衡,接下來我們測試主節點挂掉,從節點會不會自動頂上,打開主節點機器,檢視相關程序,殺死Nginx,然後打開浏覽器,輸入配置的虛拟IP位址:http://192.168.206.50/edu/a.html,發現負載均衡的效果還在,說明配置成功了。

一文幫你整理掌握Nginx
一文幫你整理掌握Nginx

6.5、關閉服務

主機節點:

[[email protected] ~]# service keepalived stop
[[email protected] ~]# /usr/local/nginx/sbin/nginx -s quit
[[email protected] ~]# /usr/local/tomcat1/bin/shutdown.sh
[[email protected] ~]# /usr/local/tomcat2/bin/shutdown.sh
           

備份節點:

[[email protected] ~]# service keepalived stop
[[email protected] ~]# /usr/local/nginx/sbin/nginx -s quit
           

第七章:Nginx配置詳解

Nginx是通過配置檔案來做到各個功能的實作的。Nginx的配置檔案的格式非常合乎邏輯,學習這種格式以及如何使用這種每個部分是基礎,這将幫助我們有可能手工建立一個配置檔案。

7.1、整體結構圖

一文幫你整理掌握Nginx

7.2、配置示範圖

一文幫你整理掌握Nginx

7.3、全局塊

配置影響Nginx全局的指令。主要包括:

  • 配置運作Nginx伺服器使用者(組)
  • worker process數
  • Nginx程序
  • PID存放路徑錯誤日志的存放路徑
  • 一個Nginx程序打開的最多檔案描述符數目

例如:

#配置worker程序運作使用者(和使用者組),nobody也是一個Linux使用者,一般用于啟動程式,沒有密碼
user nobody;
#user www www;

#配置工作程序數目,根據硬體調整,通常等于CPU數量或者2倍于CPU數量
worker_processes 1;

#配置全局錯誤日志及類型,[debug | info | notice | warn | error | crit],預設是error
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#配置程序pid檔案
pid logs/nginx.pid;

#一個nginx程序打開的最多檔案描述符數目,理論值應該是最多打開檔案數(系統的值ulimit -n)與Nginx程序數相除,但是Nginx配置設定請求并不均勻,是以建議與ulimit -n的值保持一緻。
worker_rlimit_nofile 65535;
           

7.4、events塊

配置影響Nginx伺服器或與使用者的網絡連接配接。主要包括:

  • 事件驅動模型的選擇
  • 最大連接配接數的配置

例如:

#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
#epoll模型是Linux 2.6以上版本核心中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;

#單個程序最大連接配接數(最大連接配接數=連接配接數*程序數)
worker_connections 65535;
           

7.5、http塊

可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方子產品的配置。主要包括:

  • 定義MIMI-Type
  • 自定義服務日志
  • 允許sendfile方式傳輸檔案
  • 連接配接逾時時間
  • 單連接配接請求數上限

例如:

#常見的一些基礎配置
include mime.types; #檔案擴充名與檔案類型映射表
default_type application/octet-stream; #預設檔案類型
charset utf-8; #預設編碼
server_names_hash_bucket_size 128; #伺服器名字的hash表大小
client_header_buffer_size 32k; #上傳檔案大小限制
large_client_header_buffers 4 64k; #設定請求緩沖
client_max_body_size 8m; #設定請求緩沖
sendfile on; #開啟高效檔案傳輸模式,對于普通應用設為on,如果用來進行下載下傳等應用磁盤IO重負載應用,可設定為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖檔顯示不正常把這個改成off。
autoindex on; #開啟目錄清單通路,合适下載下傳伺服器,預設關閉。
tcp_nopush on; #防止網絡阻塞
tcp_nodelay on; #防止網絡阻塞
keepalive_timeout 120; #長連接配接逾時時間,機關是秒

#FastCGI相關參數是為了改善網站的性能:減少資源占用,提高通路速度。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

#gzip子產品設定
gzip on; #開啟gzip壓縮輸出
gzip_min_length 1k; #最小壓縮檔案大小
gzip_buffers 4 16k; #壓縮緩沖區
gzip_http_version 1.0; #壓縮版本(預設1.1,前端如果是squid2.5請使用1.0)
gzip_comp_level 2; #壓縮等級
gzip_types text/plain application/x-javascript text/css application/xml; #壓縮類型
gzip_vary on; #增加響應頭'Vary: Accept-Encoding'
limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連接配接數的時候需要使用
           

7.6、server塊

配置虛拟主機的相關參數,一個http中可以有多個server。主要包括:

  • 配置網絡監聽
  • 配置https服務
  • 基于名稱的虛拟主機配置
  • 基于IP的虛拟主機配置

例如:

#虛拟主機的常見配置
server {
    listen       80; #配置監聽端口
    server_name  localhost; #配置服務名
    charset utf-8; #配置字元集
    access_log  logs/host.access.log  main; #配置本虛拟主機的通路日志
    
    location / {
        root html; #root是配置伺服器的預設網站根目錄位置,預設為Nginx安裝主目錄下的html目錄
        index index.html index.htm; #配置首頁檔案的名稱
    }
    
    error_page 404             /404.html; #配置404錯誤頁面
    error_page 500 502 503 504 /50x.html; #配置50x錯誤頁面
}

#配置https服務,安全的網絡傳輸協定,加密傳輸,端口443
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;
    }
}
           

7.7、location塊

配置請求的路由,以及各種頁面的處理情況。主要包括:

  • 請求根目錄配置更改
  • 網站預設首頁配置
  • location的URI

例如:

root html; #root是配置伺服器的預設網站根目錄位置,預設為Nginx安裝主目錄下的html目錄
index index.html index.htm; #配置首頁檔案的名稱

proxy_pass http://127.0.0.1:88; #反向代理的位址
proxy_redirect off; #是否開啟重定向
#後端的Web伺服器可以通過X-Forwarded-For擷取使用者真實IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
#以下是一些反向代理的配置,可選。
client_max_body_size 10m; #允許用戶端請求的最大單檔案位元組數
client_body_buffer_size 128k; #緩沖區代理緩沖使用者端請求的最大位元組數,
proxy_connect_timeout 90; #nginx跟後端伺服器連接配接逾時時間(代理連接配接逾時)
proxy_send_timeout 90; #後端伺服器資料回傳時間(代理發送逾時)
proxy_read_timeout 90; #連接配接成功後,後端伺服器響應時間(代理接收逾時)
proxy_buffer_size 4k; #設定代理伺服器(Nginx)儲存使用者頭資訊的緩沖區大小
proxy_buffers 4 32k; #proxy_buffers緩沖區,網頁平均在32k以下的設定
proxy_busy_buffers_size 64k; #高負荷下緩沖大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;  #設定緩存檔案夾大小
           

location的URI:

描述:該指令用于比對URL

文法:

一文幫你整理掌握Nginx

通配符:

  • =:用于不含正規表達式的uri前,要求請求字元串與uri嚴格比對,如果比對成功,就停止繼續向下搜尋并立即處理該請求。
  • ~:用于表示uri包含正規表達式,并且區分大小寫。
  • ~*:用于表示uri包含正規表達式,并且不區分大小寫。
  • ^~:用于不含正規表達式的uri前,要求Nginx伺服器找到辨別uri和請求字元串比對度最高的location後,立即使用此location處理請求,而不再使用location塊中的正則uri和請求字元串做比對。

注意:如果uri包含正規表達式,則必須要有~或者~*辨別。

第八章:Nginx原理分析

8.1、Nginx的線程模型?

Nginx預設采用多程序工作方式,Nginx啟動後,會運作一個master程序和多個worker程序。其中master充當整個程序組與使用者的互動接口,同時對程序進行監護,管理worker程序來實作重新開機服務、平滑更新、更換日志檔案、配置檔案實時生效等功能。worker用來處理基本的網絡事件,worker之間是平等的,他們共同競争來處理來自用戶端的請求。

Nginx的程序模型如圖所示:

一文幫你整理掌握Nginx

8.2、worker的工作模式?

worker對于連接配接是采用争搶的模式,誰先搶到就先交給誰處理,如果想要重新更新配置,由于已經搶到任務的worker不會參與争搶,那些空閑的worker就會去争搶連接配接,拿到連接配接後會自動更新配置資訊,當那些有任務的worker完成任務後,會自動更新配置,這樣就實作了無縫熱部署。由于每個worker是獨立的程序,如果有其中的一個worker出現問題,并不會影響其它worker繼續進行争搶,在實作請求的過程,不會造成服務中斷,建議worker數和伺服器的CPU數相等是最為适宜的。

一文幫你整理掌握Nginx

8.3、如何計算worker連接配接數?

如果隻通路Nginx的靜态資源,一個發送請求會占用了woker的2個連接配接數

而如果是作為反向代理伺服器,一個發送請求會占用了woker的4個連接配接數

8.4、如何計算最大的并發數?

如果隻通路nginx的靜态資源,最大并發數量應該是:worker_connections * worker_processes / 2

而如果是作為反向代理伺服器,最大并發數量應該是:worker_connections * worker_processes / 4

歡迎加入我的知識星球,一起探讨架構,交流源碼。加入方式,長按下方二維碼噢:

一文幫你整理掌握Nginx

已在知識星球更新源碼解析如下:

一文幫你整理掌握Nginx
一文幫你整理掌握Nginx
一文幫你整理掌握Nginx
一文幫你整理掌握Nginx

最近更新《芋道 SpringBoot 2.X 入門》系列,已經 101 餘篇,覆寫了 MyBatis、Redis、MongoDB、ES、分庫分表、讀寫分離、SpringMVC、Webflux、權限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能測試等等内容。

提供近 3W 行代碼的 SpringBoot 示例,以及超 4W 行代碼的電商微服務項目。

擷取方式:點“在看”,關注公衆号并回複 666 領取,更多内容陸續奉上。

文章有幫助的話,在看,轉發吧。
謝謝支援喲 (*^__^*)