Nginx實現負載均衡功能

一、什麼是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 :
      [[email protected]] tar zxvf openssl-fips-2.0.9.tar.gz
      [[email protected]] cd openssl-fips-2.0.9
      [[email protected]] ./config && make && make install
       
      pcre:
      [[email protected]] tar zxvf pcre-8.36.tar.gz
      [[email protected]] cd pcre-8.36
      [[email protected]] ./configure && make && make install
       
      zlib:
      [[email protected]] tar zxvf zlib-1.2.8.tar.gz
      [[email protected]] cd zlib-1.2.8
      [[email protected]] ./configure && make && make install
  3. Nginx安裝(源碼包安裝,下載地址:http://nginx.org/en/download.html
  4. 查看Nginx安裝路徑
    [[email protected]] whereis nginx
  5. 檢查是否安裝成功
    [[email protected]] cd /usr/local/nginx/sbin
    [[email protected]] ./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文件
      [[email protected]] cd /etc/init.d
      [[email protected]] 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文件顯示白色,表示權限不夠,授權
      [[email protected]] chmod 755 nginx
    • 將nginx服務加入chkconfig管理列表
      [[email protected]] 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中:

    [[email protected] 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 會出現兩臺服務器頁面交互出現的現象
  • 實驗結論:負載均衡功能——轉發請求、故障移除、恢復添加