Nginx實現負載均衡功能

来源:https://www.cnblogs.com/wly1-6/archive/2019/02/22/10418149.html
-Advertisement-
Play Games

一、什麼是Nginx? Nginx是一款輕量級的Web 伺服器、反向代理伺服器、電子郵件(IMAP/POP3)代理伺服器。 二、Nginx的優點: 三、什麼是正向代理/反向代理? 正向代理:是一個位於客戶端和原始伺服器(origin server)之間的伺服器,為了從原始伺服器取得內容,客戶端向代理 ...


一、什麼是Nginx?

Nginx是一款輕量級的Web 伺服器、反向代理伺服器、電子郵件(IMAP/POP3)代理伺服器。

二、Nginx的優點:

  1. 高併發連接:官方測試Nginx能夠支撐5萬併發連接,實際測試可達到3萬左右,每天可以處理億次訪問量;原因是:採用最新epoll(linux2.6內核)和kqueue(freebsd)網路I/O模型,而Apache採用的是傳統的select模型
  2. 記憶體消耗小
  3. Nginx支持負載均衡
  4. Nginx支持反向代理
  5. 成本低廉

三、什麼是正向代理/反向代理?

  • 正向代理:是一個位於客戶端和原始伺服器(origin server)之間的伺服器,為了從原始伺服器取得內容,客戶端向代理髮送一個請求並指定目標(原始伺服器),然後代理向原始伺服器轉交請求並將獲得的內容返回給客戶端。客戶端必須要進行一些特別的設置才能使用正向代理。
  • 反向代理:客戶端發送請求給反向代理伺服器,但是代理伺服器上沒有客戶端需要的資源,代理伺服器會判斷轉發到原始伺服器獲得資源,並把資源返回給客戶端;在整個過程,客戶端不知道自己訪問的是一個代理伺服器,而是一個原始伺服器
  • 總結:正向代理代理的是客戶端;反向代理代理的是伺服器

四、Nginx安裝(安裝Nginx所依賴的環境均用rpm包安裝,Nginx用源碼包安裝)

  1. 構建編譯環境 
    yum install -y gcc gcc-c++
  2. Nginx安裝需要依賴以下三個包(此處安裝rpm包)
    • gzip 模塊需要 zlib 庫( 下載源碼包:http://www.zlib.net/):zlib 庫提供了很多種壓縮和解壓縮的方式, nginx 使用 zlib 對 http 包的內容進行 gzip ,所以需要在 Centos 上安裝 zlib 庫。 
      yum install -y zlib zlib-devel
    • rewrite 模塊需要 pcre 庫( 下載源碼包:http://www.pcre.org/):PCRE(Perl Compatible Regular Expressions) 是一個Perl庫,包括 perl 相容的正則表達式庫。nginx 的 http 模塊使用 pcre 來解析正則表達式,所以需要在 linux 上安裝 pcre 庫,pcre-devel 是使用 pcre 開發的一個二次開發庫。nginx也需要此庫。命令:
       yum install -y pcre pcre-devel 
    • ssl 功能需要 openssl 庫( 下載:http://www.openssl.org/):OpenSSL 是一個強大的安全套接字層密碼庫,囊括主要的密碼演算法、常用的密鑰和證書封裝管理功能及 SSL 協議,並提供豐富的應用程式供測試或其它目的使用。nginx 不僅支持 http 協議,還支持 https(即在ssl協議上傳輸http),所以需要在 Centos 安裝 OpenSSL 庫。 
      yum install -y openssl openssl-devel 
    • 此處提供三個依賴包源碼包安裝方式(rpm包安裝和源碼包安裝選擇一種即可):
      openssl :
      [root@localhost] tar zxvf openssl-fips-2.0.9.tar.gz
      [root@localhost] cd openssl-fips-2.0.9
      [root@localhost] ./config && make && make install
       
      pcre:
      [root@localhost] tar zxvf pcre-8.36.tar.gz
      [root@localhost] cd pcre-8.36
      [root@localhost] ./configure && make && make install
       
      zlib:
      [root@localhost] tar zxvf zlib-1.2.8.tar.gz
      [root@localhost] cd zlib-1.2.8
      [root@localhost] ./configure && make && make install
  3. Nginx安裝(源碼包安裝,下載地址:http://nginx.org/en/download.html
    • 用Xftp將nginx-x.x.x.tar.gz從本地上傳到linux(嚴格上傳至/usr/local路徑下)
    • 解壓,得到nginx-x.x.x文件
      [root@localhost] tar -zvxf nginx-x.x.x.tar.g
      [root@localhost] cd nginx-x.x.x
      [root@localhost] ./configure && make && make install

  4. 查看Nginx安裝路徑
    [root@localhost] whereis nginx
  5. 檢查是否安裝成功
    [root@localhost] cd /usr/local/nginx/sbin
    [root@localhost] ./nginx -t
    
    顯示結果:
      nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
      nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
  6. Nginx腳本文件配置(由於是源碼包安裝,所以Nginx相關命令只能在sbin目錄下運行,過於繁瑣,現在把Nginx命令的腳本文件添加到系統服務,就可以直接用server命令service nginx ~來操作Nginx)
    • 首先進入/etc/init.d創建並編輯nginx文件,將Nginx腳本填入nginx文件
      [root@localhost] cd /etc/init.d
      [root@localhost] vim nginx

      Nginx腳本文件(官方提供腳本https://www.nginx.com/resources/wiki/start/topics/examples/redhatnginxinit/):

      #!/bin/sh
      #
      # nginx - this script starts and stops the nginx daemon
      #
      # chkconfig:   - 85 15
      # description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
      #               proxy and IMAP/POP3 proxy server
      # processname: nginx
      # config:      /etc/nginx/nginx.conf
      # config:      /etc/sysconfig/nginx
      # pidfile:     /var/run/nginx.pid
      
      # Source function library.
      . /etc/rc.d/init.d/functions
      
      # Source networking configuration.
      . /etc/sysconfig/network
      
      # Check that networking is up.
      [ "$NETWORKING" = "no" ] && exit 0
      
      nginx="/usr/local/nginx/sbin/nginx"
      prog=$(basename $nginx)
      
      NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
      
      [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
      
      lockfile=/var/lock/subsys/nginx
      
      make_dirs() {
         # make required directories
         user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
         if [ -n "$user" ]; then
            if [ -z "`grep $user /etc/passwd`" ]; then
               useradd -M -s /bin/nologin $user
            fi
            options=`$nginx -V 2>&1 | grep 'configure arguments:'`
            for opt in $options; do
                if [ `echo $opt | grep '.*-temp-path'` ]; then
                    value=`echo $opt | cut -d "=" -f 2`
                    if [ ! -d "$value" ]; then
                        # echo "creating" $value
                        mkdir -p $value && chown -R $user $value
                    fi
                fi
             done
          fi
      }
      
      start() {
          [ -x $nginx ] || exit 5
          [ -f $NGINX_CONF_FILE ] || exit 6
          make_dirs
          echo -n $"Starting $prog: "
          daemon $nginx -c $NGINX_CONF_FILE
          retval=$?
          echo
          [ $retval -eq 0 ] && touch $lockfile
          return $retval
      }
      
      stop() {
          echo -n $"Stopping $prog: "
          killproc $prog -QUIT
          retval=$?
          echo
          [ $retval -eq 0 ] && rm -f $lockfile
          return $retval
      }
      
      restart() {
          configtest || return $?
          stop
          sleep 1
          start
      }
      
      reload() {
          configtest || return $?
          echo -n $"Reloading $prog: "
          killproc $nginx -HUP
          RETVAL=$?
          echo
      }
      
      force_reload() {
          restart
      }
      
      configtest() {
        $nginx -t -c $NGINX_CONF_FILE
      }
      
      rh_status() {
          status $prog
      }
      
      rh_status_q() {
          rh_status >/dev/null 2>&1
      }
      
      case "$1" in
          start)
              rh_status_q && exit 0
              $1
              ;;
          stop)
              rh_status_q || exit 0
              $1
              ;;
          restart|configtest)
              $1
              ;;
          reload)
              rh_status_q || exit 7
              $1
              ;;
          force-reload)
              force_reload
              ;;
          status)
              rh_status
              ;;
          condrestart|try-restart)
              rh_status_q || exit 0
                  ;;
          *)
              echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
              exit 2
      esac
      註意:  將以上腳本保存到/etc/init.d/nginx文件,並修改兩個地方:
      • nginx=”/usr/sbin/nginx” 修改成nginx執行程式的路徑。
      • NGINX_CONF_FILE=”/etc/nginx/nginx.conf” 修改成配置文件的路徑。
    • nginx文件顯示白色,表示許可權不夠,授權
      [root@localhost] chmod 755 nginx
    • 將nginx服務加入chkconfig管理列表
      [root@localhost] chkconfig --add /etc/init.d/nginx
  7. 設置Nginx開機自啟
    vim /etc/rc.local
    增加一行 /usr/local/nginx/sbin/nginx
    設置執行許可權:
    chmod 755 rc.local          

  8. 至此,Nginx安裝完畢

五、Nginx負載均衡實現

  • 搭建環境

   準備三台linux(一臺用作Nginx負載均衡伺服器,另外兩台配置app真實伺服器)

  • Nginx負載均衡器配置:在預設安裝的Nginx配置文件Nginx.conf中:

    [root@bogon html]# cat /usr/local/nginx/conf/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 serverCluster{
            server 192.168.182.131:8080 weight=1;
            server 192.168.182.133:8080 weight=1;
        }
        server {
            listen       80;
            server_name  localhost;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
    
            location / {
                root   html;
                index  index.html index.htm;
            }
    
            #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;
        #    }
        #}
    
        server{
            listen  80;
            server_name  www.test.com;
            index  index.jsp index.html index.htm;
            root  /data/www;
        
            location /{
                proxy_next_upstream http_502 http_504 error timeout invalid_header;  
                proxy_set_header Host $host;  
                proxy_set_header X-Real-IP $remote_addr;  
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
                proxy_pass http://serverCluster;  
                expires   3d;  
            }
        }
        # 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;
        #    }
        #}
    
    }
  • APP真實伺服器搭建(tomcat伺服器):

    • JDK安裝:下載地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html
      • 下載JDK的tar.gz包jdk-8u151-linux-i586.tar.gz
      • 用Xftp將JDK的源碼包上傳至linux系統的/root文件中然後
      • 解壓源碼包至/opt中,並改名為jdk
        tar -zxvf  jdk-8u151-linux-i586.tar.gz      //解壓
        mv  jdk1.8.1_151  /opt                      //移動文件
        mv  jdk1.8.1_151  jdk                       //更名
      • 配置環境變數
        vim /etc/profile
        在/etc/profile 文件的結尾添加所需編輯內容:
        export JAVA_HOME=/opt/jdk          //這裡是你的jdk的安裝目錄  
        export PATH=$JAVA_HOME/bin:$PATH
        export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
      • 執行使配置信息馬上生效的命令source
        source /etc/profile               // 這條命令是讓配置馬上生效。
      • 測試jdk安裝結果
        java –version                     //顯示java版本信息表示JDK安裝完成
    • Tomcat安裝:下載地址:http://tomcat.apache.org
      • 下載與jdk版本對應的tomcat版本apache-tomcat-8.5.24.tar.gz
      • 用Xftp將apache-tomcat-8.5.24.tar.gz上傳至/root目錄
      • 解壓apache-tomcat-8.5.24.tar.gz至/opt目錄,並更名為tomcat
        tar -zvxf apache-tomcat-8.5.24.tar.gz    //解壓文件
        mv apache-tomcat-8.5.24 /opt             //轉移文件
        mv apache-tomcat-8.5.24 tomcat           //文件更名
      • 關閉防火牆
        service iptables stop
        chkconfig iptables off
      • 測試tomcat安裝結果:打開瀏覽器,訪問http://虛擬機IP地址:8080,出現Tom貓,則表示安裝成功
  • 測試Nginx負載均衡

   (真實伺服器IP1:192.168.182.131;真實伺服器IP2:192.168.182.132;nginx伺服器IP:192.168.182.130)

    • 測試前工作(此處我修改為一個顯示APP1,另一個顯示APP2)

       因為兩台tomcat伺服器測試跳轉的頁面都是Tom貓,為了顯示負載均衡效果,需要更改tomcat伺服器的顯示頁面;

       顯示頁面位於/opt/tomcat/webapps/ROOT路徑的index.jsp頁面,故只需在此路徑下編輯一個index.html頁面,就會取代原先的index.jsp,因為/opt/tomcat/conf/web.xml中的歡迎頁面的順序是index.html>index.jsp

    • 打開瀏覽器,訪問Nginx配置文件nginx.conf中配置的代理功能變數名稱www.test.com(此處需要註意的時,www.test.com這個功能變數名稱和nginx伺服器IP192.168.182.130並沒有通過DNS功能變數名稱解析服務,所以需要在本機的hosts文件中進行配置功能變數名稱和IP的映射關係,具體配置不再展示,如果不配置,則nginx配置文件中不能使用www.test.com來作為http_server模塊server_name的值,只能寫具體的IP,即nginx伺服器的IP),因為nginx配置中監控的埠是80,故不需要添加埠
    • 結果就是:顯示界面分別為兩台tomcat中配置的自定義顯示界面輪流出現
    • 關閉一臺tomcat伺服器後,再訪問www.test.com,只會出現另一臺tomcat的頁面,再開啟這台tomcat伺服器後,再訪問www.test.com 會出現兩台伺服器頁面交互出現的現象
  • 實驗結論:負載均衡功能——轉發請求、故障移除、恢復添加

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在使用childNodes時,發現需要刪除的元素多於1時,會出現無法全部刪除的情況。谷歌以後發現,該屬性返回的子節點集合是實時更新的,也就是說,在for迴圈中,當刪除第一個子節點之後,第二次刪除的是原子節點集合中的第三個元素。故需要刪除全部子節點時,使用 在MDN中查了一下,childNodes返回 ...
  • 這幾天,博主碰到了幾道關於數字轉漢字的javascript演算法題,在網上找了很多的答案,發現都有點複雜,於是我決定自己寫一篇關於這種演算法題的簡單解法,以下是博主自己的見解,有不足的地方請多指教。 接下來,我給大家講解一下幾道類似的例題 一、單個數字轉漢字的解決方法 1.利用數組存儲0-9的漢字,代碼 ...
  • 需求的表格比較複雜(各種合併新增刪除),elementUi的table組件無法滿足需求,故而寫了原生table,且與其他用了table組件的表格保持一致。 貼一下簡單的代碼,只實現操作按鈕固定右側以及底部滾動條功能: <!DOCTYPE html> <html lang="en"> <head> < ...
  • 想清楚思路很有必要!需要一個空的數組來存放準備掩膜的要素ID var map = new WebScene({ portalItem:{id:"10ede348e4c54c77b45f6ebab2d018db"} }); var view = new SceneView({ container:"v ...
  • 本文由雲+社區發表 作者:騰訊ISUX 項目背景 2019年春節期間,QQ紅包運營活動進行了全新改版,將卡券福利、現金獎勵打包成福袋形式,並通過年俗小游戲及共用福袋的玩法吸引更多用戶參與。在點擊福袋進入小游戲的界面,我們推出了QQ空間新春福袋品牌視頻,希望用戶在等待載入的過程中感受到新春氛圍,同時也 ...
  • 一直以來都是在寫項目卻從來沒有仔細分析過什麼是單例模式,單例模式分為幾種,單例模式有什麼特點。今天隨便記錄一個隨筆,全當是複習複習做個筆記。 單例模式要確保某個類只有一個實例,而且自動實例化並向整個系統提供實例。單例模式分為3種:餓漢單例模式、懶漢單例模式、登記式單例模式。 單例模式有3個特點: 單 ...
  • LieBrother原文: "行為型模式:命令模式" 十一大行為型模式之三:命令模式。 簡介 姓名 :命令模式 英文名 :Command Pattern 價值觀 :軍令如山 個人介紹 : Encapsulate a request as an object,thereby letting you p ...
  • kafka_2.11-0.9.0.1.tgz 1.進入項目前的目錄 cd /home/dongshanxia mkdir kafka #創建項目目錄 cd kafka #進入項目目錄 mkdir kafkalogs #創建kafka消息目錄,主要存放kafka消息 2.進入配置文件目錄 cd /ho ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...