经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Nginx » 查看文章
Nginx实现负载均衡功能
来源:cnblogs  作者:^^ITBOY^^  时间:2019/2/25 9:28:27  对本文有异议

一、什么是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. 构建编译环境 

    1. yum install -y gcc gcc-c++
  2. Nginx安装需要依赖以下三个包(此处安装rpm包)

    • gzip 模块需要 zlib 库( 下载源码包:http://www.zlib.net/):zlib 库提供了很多种压缩和解压缩的方式, nginx 使用 zlib 对 http 包的内容进行 gzip ,所以需要在 Centos 上安装 zlib 库。 

      1. 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也需要此库。命令:

      1.  yum install -y pcre pcre-devel
    • ssl 功能需要 openssl 库( 下载:http://www.openssl.org/):OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL 协议,并提供丰富的应用程序供测试或其它目的使用。nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http),所以需要在 Centos 安装 OpenSSL 库。 

      1. yum install -y openssl openssl-devel
    • 此处提供三个依赖包源码包安装方式(rpm包安装和源码包安装选择一种即可):

      1. openssl 
      2. [root@localhost] tar zxvf openssl-fips-2.0.9.tar.gz
      3. [root@localhost] cd openssl-fips-2.0.9[root@localhost] ./config && make && make install pcre:
      4. [root@localhost] tar zxvf pcre-8.36.tar.gz
      5. [root@localhost] cd pcre-8.36[root@localhost] ./configure && make && make install zlib:
      6. [root@localhost] tar zxvf zlib-1.2.8.tar.gz
      7. [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文件

      1. [root@localhost] tar -zvxf nginx-x.x.x.tar.g
      2. [root@localhost] cd nginx-x.x.x
      3. [root@localhost] ./configure && make && make install

  4. 查看Nginx安装路径

    1. [root@localhost] whereis nginx
  5. 检查是否安装成功

    1. [root@localhost] cd /usr/local/nginx/sbin
    2. [root@localhost] ./nginx -t
    3.  
    4. 显示结果:
    5.   nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
    6.   nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
  6. Nginx脚本文件配置(由于是源码包安装,所以Nginx相关命令只能在sbin目录下运行,过于繁琐,现在把Nginx命令的脚本文件添加到系统服务,就可以直接用server命令service nginx ~来操作Nginx)

    • nginx=”/usr/sbin/nginx” 修改成nginx执行程序的路径。

    • NGINX_CONF_FILE=”/etc/nginx/nginx.conf” 修改成配置文件的路径。

    • 首先进入/etc/init.d创建并编辑nginx文件,将Nginx脚本填入nginx文件

      1. [root@localhost] cd /etc/init.d
      2. [root@localhost] vim nginx

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

      1. #!/bin/sh
      2. #
      3. # nginx - this script starts and stops the nginx daemon
      4. #
      5. # chkconfig:   - 85 15# description:  NGINX is an HTTP(S) server, HTTP(S) reverse #               proxy and IMAP/POP3 proxy server
      6. # processname: nginx
      7. # config:      /etc/nginx/nginx.conf
      8. # config:      /etc/sysconfig/nginx
      9. # pidfile:     /var/run/nginx.pid
      10.  
      11. # Source function library.
      12. . /etc/rc.d/init.d/functions
      13.  
      14. # Source networking configuration.
      15. . /etc/sysconfig/network
      16.  
      17. # Check that networking is up.
      18. [ "$NETWORKING" = "no" ] && exit 0nginx="/usr/local/nginx/sbin/nginx"prog=$(basename $nginx)NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"[ -/etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
      19.  
      20. lockfile=/var/lock/subsys/nginx
      21.  
      22. make_dirs() {
      23.    # make required directories
      24.    user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`   if [ -"$user" ]; then      if [ -"`grep $user /etc/passwd`" ]; then
      25.          useradd --/bin/nologin $user
      26.       fi
      27.       options=`$nginx -V 2>&1 | grep 'configure arguments:'`      for opt in $options; do  if [ `echo $opt | grep '.*-temp-path'` ]; then
      28.               value=`echo $opt | cut -d "=" -f 2`              if [ ! -"$value" ]; then
      29.                   # echo "creating" $value
      30.                   mkdir -p $value && chown -R $user $value
      31.               fi
      32.           fi
      33.        done
      34.     fi
      35. }
      36.  
      37. start() {
      38.     [ -x $nginx ] || exit 5[ -f $NGINX_CONF_FILE ] || exit 6make_dirs
      39.     echo -n $"Starting $prog: "daemon $nginx -c $NGINX_CONF_FILE
      40.     retval=$?echo
      41.     [ $retval -eq 0 ] && touch $lockfilereturn $retval
      42. }
      43.  
      44. stop() {
      45.     echo -n $"Stopping $prog: "killproc $prog -QUIT
      46.     retval=$?echo
      47.     [ $retval -eq 0 ] && rm -f $lockfilereturn $retval
      48. }
      49.  
      50. restart() {
      51.     configtest || return $?stop
      52.     sleep 1start
      53. }
      54.  
      55. reload() {
      56.     configtest || return $?echo -n $"Reloading $prog: "killproc $nginx -HUP
      57.     RETVAL=$?echo
      58. }
      59.  
      60. force_reload() {
      61.     restart
      62. }
      63.  
      64. configtest() {
      65.   $nginx --c $NGINX_CONF_FILE
      66. }
      67.  
      68. rh_status() {
      69.     status $prog
      70. }
      71.  
      72. rh_status_q() {
      73.     rh_status >/dev/null 2>&1}case "$1" in
      74.     start)
      75.         rh_status_q && exit 0$1;;
      76.     stop)
      77.         rh_status_q || exit 0$1;;
      78.     restart|configtest)
      79.         $1;;
      80.     reload)
      81.         rh_status_q || exit 7$1;;
      82.     force-reload)
      83.         force_reload
      84.         ;;
      85.     status)
      86.         rh_status
      87.         ;;
      88.     condrestart|try-restart)
      89.         rh_status_q || exit 0;;*)
      90.         echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"exit 2esac

      注意:

       将以上脚本保存到/etc/init.d/nginx文件,并修改两个地方:

    • nginx文件显示白色,表示权限不够,授权

      1. [root@localhost] chmod 755 nginx
    • 将nginx服务加入chkconfig管理列表

      1. [root@localhost] chkconfig --add /etc/init.d/nginx
  7. 设置Nginx开机自启

    1. vim /etc/rc.local
    2. 增加一行 /usr/local/nginx/sbin/nginx
    3. 设置执行权限:
    4. chmod 755 rc.local

  8. 至此,Nginx安装完毕

五、Nginx负载均衡实现

  • 搭建环境

   准备三台linux(一台用作Nginx负载均衡服务器,另外两台配置app真实服务器)

  • Nginx负载均衡器配置:在默认安装的Nginx配置文件Nginx.conf中:

    1. [root@bogon html]# cat /usr/local/nginx/conf/nginx.conf
    2.  
    3. #user  nobody;
    4. worker_processes  1;
    5.  
    6. #error_log  logs/error.log;
    7. #error_log  logs/error.log  notice;
    8. #error_log  logs/error.log  info;
    9.  
    10. #pid        logs/nginx.pid;
    11.  
    12.  
    13. events {
    14.     worker_connections  1024;
    15. }
    16.  
    17.  
    18. http {
    19.     include       mime.types;
    20.     default_type  application/octet-stream;
    21.  
    22.     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '#                  '$status $body_bytes_sent "$http_referer" '#                  '"$http_user_agent" "$http_x_forwarded_for"';
    23.  
    24.     #access_log  logs/access.log  main;
    25.  
    26.     sendfile        on;
    27.     #tcp_nopush     on;
    28.  
    29.     #keepalive_timeout  0;
    30.     keepalive_timeout  65;
    31.  
    32.     gzip  on;upstream serverCluster{
    33.         server 192.168.182.131:8080 weight=1;
    34.         server 192.168.182.133:8080 weight=1;
    35.     }server {
    36.         listen       80;
    37.         server_name  localhost;
    38.  
    39.         #charset koi8-r;
    40.  
    41.         #access_log  logs/host.access.log  main;
    42.  
    43.         location / {
    44.             root   html;
    45.             index  index.html index.htm;
    46.         }
    47.  
    48.         #error_page  404              /404.html;
    49.  
    50.         # redirect server error pages to the static page /50x.html
    51.         #
    52.         error_page   500 502 503 504  /50x.html;
    53.         location = /50x.html {
    54.             root   html;
    55.         }
    56.  
    57.         # proxy the PHP scripts to Apache listening on 127.0.0.1:80#
    58.         #location ~ \.php$ {
    59.         #    proxy_pass   http://127.0.0.1;        #}
    60.  
    61.         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000#
    62.         #location ~ \.php$ {
    63.         #    root           html;
    64.         #    fastcgi_pass   127.0.0.1:9000;
    65.         #    fastcgi_index  index.php;
    66.         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    67.         #    include        fastcgi_params;
    68.         #}
    69.  
    70.         # deny access to .htaccess files, if Apache's document root
    71.         # concurs with nginx's one        #
    72.         #location ~ /\.ht {
    73.         #    deny  all;
    74.         #}
    75.     }
    76.  
    77.  
    78.     # another virtual host using mix of IP-, name-, and port-based configuration
    79.     #
    80.     #server {
    81.     #    listen       8000;
    82.     #    listen       somename:8080;
    83.     #    server_name  somename  alias  another.alias;
    84.  
    85.     #    location / {
    86.     #        root   html;
    87.     #        index  index.html index.htm;
    88.     #    }
    89.     #}server{listen  80;
    90.         server_name  www.test.com;index  index.jsp index.html index.htm;
    91.         root  /data/www;
    92.     
    93.         location /{
    94.             proxy_next_upstream http_502 http_504 error timeout invalid_header;  
    95.             proxy_set_header Host $host;  
    96.             proxy_set_header X-Real-IP $remote_addr;  
    97.             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
    98.             proxy_pass http://serverCluster;              expires   3d;  
    99.         }
    100.     }# HTTPS server
    101.     #
    102.     #server {
    103.     #    listen       443 ssl;
    104.     #    server_name  localhost;
    105.  
    106.     #    ssl_certificate      cert.pem;
    107.     #    ssl_certificate_key  cert.key;
    108.  
    109.     #    ssl_session_cache    shared:SSL:1m;
    110.     #    ssl_session_timeout  5m;
    111.  
    112.     #    ssl_ciphers  HIGH:!aNULL:!MD5;
    113.     #    ssl_prefer_server_ciphers  on;
    114.  
    115.     #    location / {
    116.     #        root   html;
    117.     #        index  index.html index.htm;
    118.     #    }
    119.     #}
    120.  
    121. }
  • APP真实服务器搭建(tomcat服务器):

    • 下载与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

      1. tar -zvxf apache-tomcat-8.5.24.tar.gz    //解压文件mv apache-tomcat-8.5.24 /opt             //转移文件mv apache-tomcat-8.5.24 tomcat           //文件更名
    • 关闭防火墙

      1. service iptables stop
      2. chkconfig iptables off
    • 测试tomcat安装结果:打开浏览器,访问http://虚拟机IP地址:8080,出现Tom猫,则表示安装成功

    • 下载JDK的tar.gz包jdk-8u151-linux-i586.tar.gz

    • 用Xftp将JDK的源码包上传至linux系统的/root文件中然后

    • 解压源码包至/opt中,并改名为jdk

      1. tar -zxvf  jdk-8u151-linux-i586.tar.gz      //解压mv  jdk1.8.1_151  /opt                      //移动文件mv  jdk1.8.1_151  jdk                       //更名
    • 配置环境变量

      1. vim /etc/profile

      在/etc/profile 文件的结尾添加所需编辑内容:

      1. export JAVA_HOME=/opt/jdk          //这里是你的jdk的安装目录  export PATH=$JAVA_HOME/bin:$PATH
      2. export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
    • 执行使配置信息马上生效的命令source

      1. source /etc/profile               // 这条命令是让配置马上生效。
    • 测试jdk安装结果

      1. java –version                     //显示java版本信息表示JDK安装完成
    • JDK安装:下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html

    • Tomcat安装:下载地址:http://tomcat.apache.org

    • 测试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 会出现两台服务器页面交互出现的现象

    • 实验结论:负载均衡功能——转发请求、故障移除、恢复添加

     

    原文链接:http://www.cnblogs.com/wly1-6/p/10418149.html

     友情链接:直通硅谷  点职佳  北美留学生论坛

    本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

    W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
    关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
    皖ICP备17017327号-2 皖公网安备34020702000426号