一文幫你整理掌握 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 個併發連接數。

第二章: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

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、啓動後效果

第三章:Nginx 反向代理

3.1、概述

Nginx 不僅可以做反向代理,還能用作正向代理來進行上網等功能,正向代理:如果把局域網外的 Internet 想象成一個巨大的資源庫,則局域網中的客戶端要訪問 Internet,則需要通過代理服務器來訪問,這種代理服務就稱爲正向代理。對於反向代理,客戶端對代理是無感知的,因爲客戶端不需要任何配置就可以訪問,我們只需要將請求發送到反向代理服務器,由反向代理服務器去選擇目標服務器獲取數據後,在返回給客戶端,此時反向代理服務器和目標服務器對外就是一個服務器,暴露的是代理服務器地址,隱藏了真實服務器 IP 地址。

3.2、配置反向代理實例 1

3.2.1、實現效果

打開瀏覽器,在瀏覽器地址欄輸入地址:http://www.123.com,跳轉到 Liunx 系統 Tomcat 主頁面中。

3.2.2、實現思路

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 反向代理,根據訪問的路徑跳轉到不同端口的服務中。

3.3.2、實現思路

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 class />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener class />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener class />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener class />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener class />
  <Listener class />
  <Listener class />
  <!-- 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 
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              path />
  </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 >
    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor 
        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 >
    -->
    <Engine >
      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster class/>
      -->
      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm class>
        <!-- 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 class
               resource/>
      </Realm>
      <Host 
            unpackWARs="true" autoDeploy="true">
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve class />
        -->
        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve class
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %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

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

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。

語法:

通配符:

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

第四章:Nginx 負載均衡

4.1、概述

客戶端發送多個請求到服務器,服務器處理請求,有一些可能要與數據庫進行交互,服務器處理完畢後,再將結果返回給客戶端。

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

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

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

4.2、實現效果

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

4.3、實現思路

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

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

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 掉,能自動剔除。

weight:weight 代表權重,默認爲 1,權重越高被分配的客戶端越多,weight 和訪問比率成正比,用於後端服務器性能不均的情況。例如:

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

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

第五章:Nginx 動靜分離

5.1、概述

Nginx 動靜分離簡單來說就是把動態跟靜態請求分開,不能理解成只是單純的把動態頁面和靜態頁面物理分離。嚴格意義上說應該是動態請求跟靜態請求分開,可以理解成使用 Nginx 處理靜態頁面,Tomcat 處理動態頁面。動靜分離從目前實現角度來講大致分爲兩種,一種是純粹把靜態文件獨立成單獨的域名,放在獨立的服務器上,也是目前主流推崇的方案;另外一種方法就是動態跟靜態文件混合在一起發佈,通過 Nginx 來分開。

5.2、實現效果

如果不設置動靜分離,默認會通過 Nginx 的反向代理去找 Tomcat 對應的資源,現在我們在根目錄下創建一個 / data/www / 文件夾,裏邊放上靜態資源,比如一個 html 頁面,在 8080 的那臺 Tomcat 的 WebApps 下也創建一個 www 目錄,同樣是放一個靜態資源,當輸入這個靜態資源的請求時,訪問到的是 / data/www 中的數據。

5.3、實現思路

5.4、實現步驟

第一步:創建靜態資源文件,爲了對比,Tomcat 中也放一個

[root@caochenlei ~]# mkdir -p /data/www/
[root@caochenlei ~]# mkdir -p /usr/local/tomcat/webapps/ROOT/www
[root@caochenlei ~]# echo "/data/www/a.html" > /data/www/a.html
[root@caochenlei ~]# echo "/usr/local/tomcat/webapps/ROOT/www/a.html" > /usr/local/tomcat/webapps/ROOT/www/a.html

第二步:修改 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 /www/ {
            root /data/;
            index index.html index.htm;
        }
[root@caochenlei ~]# /usr/local/nginx/sbin/nginx

第三步:啓動 Tomcat

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

第四步:啓動瀏覽器進行測試

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

5.5、關閉服務

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

第六章:Nginx 高可用集羣

6.1、概述

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

6.2、實現效果

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

6.3、實現思路

6.4、實現步驟

第一步:修改主

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

節點上的 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

第二步:啓動主節點上的兩臺 Tomcat

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

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

安裝 keepalived:

[root@caochenlei ~]# yum install -y keepalived

刪除 keepalived 的配置文件:

[root@caochenlei ~]# rm -f /etc/keepalived/keepalived.conf

新增 keepalived 的配置文件:

[root@caochenlei ~]# vi /etc/keepalived/keepalived.conf

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

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   #郵件服務器通知地址(暫不配置,默認即可)
   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 的檢測腳本:

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

啓動 keepalived 服務:

[root@caochenlei ~]# service keepalived start

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

啓動虛擬機:

安裝 Nginx 依賴:

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

下載 Nginx 文件:

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

安裝 Nginx 程序:

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

開放 Nginx 防火牆:

[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:     [確定]

修改 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;
        }

啓動 Nginx 的服務:

[root@caochenlei ~]# /usr/local/nginx/sbin/nginx

安裝 keepalived:

[root@caochenlei ~]# yum install -y keepalived

刪除 keepalived 的配置文件:

[root@caochenlei ~]# rm -f /etc/keepalived/keepalived.conf

新增 keepalived 的配置文件:

[root@caochenlei ~]# vi /etc/keepalived/keepalived.conf

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

! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   #郵件服務器通知地址(暫不配置,默認即可)
   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 的檢測腳本:

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

啓動 keepalived 服務:

[root@caochenlei ~]# service keepalived start

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

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

按住 F5 多刷新兩遍,看看會不會,將請求轉發到 Tomcat2 中去。

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

按住 F5 多刷新兩遍,看看會不會,將請求轉發到 Tomcat2 中去。

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

按住 F5 多刷新兩遍,看看會不會,將請求轉發到 Tomcat2 中去。

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

6.5、關閉服務

主機節點:

[root@caochenlei ~]# service keepalived stop
[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

備份節點:

[root@caochenlei ~]# service keepalived stop
[root@caochenlei ~]# /usr/local/nginx/sbin/nginx -s quit

第七章:Nginx 配置詳解

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

7.1、整體結構圖

7.2、配置演示圖

7.3、全局塊

配置影響 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,配置代理,緩存,日誌定義等絕大多數功能和第三方模塊的配置。主要包括:

例如:

#常見的一些基礎配置
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。主要包括:

例如:

#虛擬主機的常見配置
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 塊

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

例如:

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

語法:

通配符:

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

第八章:Nginx 原理分析

8.1、Nginx 的線程模型?

Nginx 默認採用多進程工作方式,Nginx 啓動後,會運行一個 master 進程和多個 worker 進程。其中 master 充當整個進程組與用戶的交互接口,同時對進程進行監護,管理 worker 進程來實現重啓服務、平滑升級、更換日誌文件、配置文件實時生效等功能。worker 用來處理基本的網絡事件,worker 之間是平等的,他們共同競爭來處理來自客戶端的請求。

Nginx 的進程模型如圖所示:

8.2、worker 的工作模式?

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

8.3、如何計算 worker 連接數?

如果只訪問 Nginx 的靜態資源,一個發送請求會佔用了 woker 的 2 個連接數

而如果是作爲反向代理服務器,一個發送請求會佔用了 woker 的 4 個連接數

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

如果只訪問 nginx 的靜態資源,最大併發數量應該是:worker_connections * worker_processes / 2

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

作者:輕鬆的小希

來源:blog.csdn.net/qq_38490457/article/details/108300342

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/t5ieKlybDQCxLLlQDzW2HA