美文网首页运维部署我爱编程
nginx负载均衡+缓存实例

nginx负载均衡+缓存实例

作者: 小尛酒窝 | 来源:发表于2018-05-28 21:56 被阅读395次

    背景介绍

    背景拓扑

    部署Lnmp环境,在gw上做nginx负载均衡,将访问wordpress和pma的页面资源负载均衡到nginx1、nginx2上。
    同时在gw上启用proxy-cache,然后对相关页面进行压测,观察比较启动缓存前与缓存后的访问速度。

    注意:在实验中确保每个服务器的firewalld为关闭状态及selinux为permissive状态。

    1、搭建应用服务器

    安装PHP-fpm和数据库等相关程序

    [root@app ~]# yum install php php-fpm php-mcrypt php-mysql php-mbstring mariadb-server -y
    

    编辑/etc/php-fpm.d/www.conf的内容:

    [root@app ~]# vim /etc/php-fpm.d/www.conf
    listen = 0.0.0.0:9000
    listen.allowed_clients = 10.10.10.11,10.10.10.12
    pm.status_path = /status
    ping.path = /ping
    ping.response = pong
    php_value[session.save_path] = /var/lib/php/session
    

    随后创建会话目录并更改会话目录的属主属组:

    [root@app ~]# mkdir -pv /var/lib/php/session
    mkdir: created directory ‘/var/lib/php/session’
    [root@app ~]# chown apache:apache /var/lib/php/session/
    

    随后启动php-fpm服务:

    drwxrwx---. 2 root apache 6 Apr 12 15:04 /var/lib/php/session/
    [root@app ~]# systemctl start php-fpm
    [root@app ~]# ss -tnl
    State       Recv-Q Send-Q                                     Local Address:Port                                                    Peer Address:Port              
    LISTEN      0      128                                                    *:22                                                                 *:*                  
    LISTEN      0      100                                            127.0.0.1:25                                                                 *:*                  
    LISTEN      0      128                                                    *:9000                                                               *:*                  
    LISTEN      0      128                                                   :::22                                                                :::*                  
    LISTEN      0      100                                                  ::1:25                                                                :::* 
    

    接着创建web资源存放目录:

    [root@app ~]# mkdir -pv /data/nginx/html
    mkdir: created directory ‘/data’
    mkdir: created directory ‘/data/nginx’
    mkdir: created directory ‘/data/nginx/html’
    

    创建php页面:

    [root@app ~]# vim /data/nginx/html/index.php
    <h1>This is app</h1>
    <?php
            phpinfo();
    ?>
    

    下载wordpress和phpMyadmin到该目录并解压生成软连接:

    [root@app ~]# cd /data/nginx/html
    [root@app html]# wget https://cn.wordpress.org/wordpress-4.9.4-zh_CN.tar.gz
    [root@app html]# wget https://files.phpmyadmin.net/phpMyAdmin/4.0.10.20/phpMyAdmin-4.0.10.20-all-languages.tar.gz
    [root@app html]# tar xf wordpress-4.9.4-zh_CN.tar.gz 
    [root@app html]# tar xf  phpMyAdmin-4.0.10.20-all-languages.tar.gz 
    [root@app html]# ln -sv phpMyAdmin-4.0.10.20-all-languages pma
    ‘pma’ -> ‘phpMyAdmin-4.0.10.20-all-languages’
    [root@app html]# ln -sv wordpress blog
    ‘blog’ -> ‘wordpress
    

    接着配置mariadb-server,编辑/etc/my.cnf文件:

    #添加下面两行配置
    [root@app ~]# vim /etc/my.cnf
    skip-name-resolve=ON
    innodb-file-per-table=ON
    

    随后启动mariadb-server服务:

    [root@app ~]# systemctl start mariadb
    

    接着设置mysql的root密码:

    [root@app ~]# mysql_secure_installation 
    
    NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
          SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
    
    In order to log into MariaDB to secure it, we'll need the current
    password for the root user.  If you've just installed MariaDB, and
    you haven't set the root password yet, the password will be blank,
    so you should just press enter here.
    
    Enter current password for root (enter for none): 
    OK, successfully used password, moving on...
    
    Setting the root password ensures that nobody can log into the MariaDB
    root user without the proper authorisation.
    
    Set root password? [Y/n] y
    New password: 
    Re-enter new password: 
    Password updated successfully!
    Reloading privilege tables..
     ... Success!
    

    在数据库中创建wordpress数据库并授权wpuser管理账号:

    MariaDB [(none)]> create database wordpress;
    Query OK, 1 row affected (0.00 sec)
    MariaDB [(none)]> grant all on wordpress.* to 'wpuser'@'192.168.0.%' identified by "magedu";
    Query OK, 0 rows affected (0.00 sec)
    

    最后检查关闭应用服务器的firewalld和selinux:

    [root@app ~]# systemctl stop firewalld
    [root@app ~]# setenforce 0
    

    2、搭建nginx服务器

    由于两个nginx服务器安装的流程及步骤类似,此处我们取一台作为示例,剩下一台的按照示例配置即可。

    首先安装nginx服务:

    
    [root@nginx1 ~]# yum install -y epel-release
    [root@nginx1 ~]# yum install -y nginx
    

    接着创建web资源存放目录:

    [root@nginx1 ~]# mkdir -pv /data/nginx/html 
    mkdir: created directory ‘/data’
    mkdir: created directory ‘/data/nginx’
    mkdir: created directory ‘/data/nginx/html’
    

    创建web主页页面:

    [root@nginx1 ~]# vim /data/nginx/html/index.html
    <h1>This is nginx 1 10.10.10.11</h1>
    

    创建php页面:

    [root@nginx1 ~]# vim /data/nginx/html/index.php
    <h1>This is nginx 1</h1>
    <?php
            phpinfo();
    ?>
    

    下载wordpress和phpMyadmin到该目录并解压生成软连接:

    [root@nginx1 ~]# cd /data/apache/html
    [root@nginx1 html]# wget https://cn.wordpress.org/wordpress-4.9.4-zh_CN.tar.gz
    [root@nginx1 html]# wget https://files.phpmyadmin.net/phpMyAdmin/4.0.10.20/phpMyAdmin-4.0.10.20-all-languages.tar.gz
    [root@nginx1 html]# tar xf wordpress-4.9.4-zh_CN.tar.gz 
    [root@nginx1 html]# tar xf  phpMyAdmin-4.0.10.20-all-languages.tar.gz 
    [root@nginx1 html]# ln -sv phpMyAdmin-4.0.10.20-all-languages pma
    ‘pma’ -> ‘phpMyAdmin-4.0.10.20-all-languages’
    [root@nginx1 html]# ln -sv wordpress blog
    ‘blog’ -> ‘wordpress
    

    编辑生成/etc/nginx/conf.d/vhosts.conf文件:

    [root@nginx1 html]# vim /etc/nginx/nginx.conf
    #注释掉默认配置文件中的80端口
    #        listen       80 default_server;
    #        listen       [::]:80 default_server;
    [root@nginx1 html]# vim /etc/nginx/conf.d/vhosts.conf
    server {
            listen 80;
            server_name www.ilinux.io;
            index index.html index.php;
            location / {
                    root /data/nginx/html;
            }
            location ~* \.php$ {
                    fastcgi_pass 10.10.10.13:9000;
                    fastcgi_index index.php;
                    include fastcgi_params;
                    fastcgi_param SCRIPT_FILENAME /data/nginx/html/$fastcgi_script_name;
            }
            location ~* /(status|ping) {
                    fastcgi_pass 10.10.10.13:9000;
                    include fastcgi_params;
                    fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
            }
    
    }
    

    最后检查并关闭firewalld和selinux:

    [root@ap1 ~]# systemctl stop firewalld
    [root@ap1 ~]# setenforce 0
    

    至此nginx服务器的配置就已经完成,按照上述步骤配置第二台服务器即可。

    3、配置nginx负载均衡服务器

    安装nginx服务:

    [root@nginx-gw ~]# yum install -y epel-release
    [root@nginx-gw ~]# yum install -y nginx
    

    编辑配置/etc/nginx/nginx.conf文件:

    [root@nginx-gw ~]# vim /etc/nginx/nginx.conf
    #在http配置段添加下面配置
    http {
        upstream webservres {
            server 10.10.10.11:8080 max_fails=3;
            server 10.10.10.12:8080 max_fails=3;
            server 127.0.0.1:80 backup;
            }
        server {
            listen       80 default_server;
            listen       [::]:80 default_server;
            server_name  _;
            root         /usr/share/nginx/html;
    
            # Load configuration files for the default server block.
            include /etc/nginx/default.d/*.conf;
    
            location / {
                    proxy_pass http://webservers;  #代理传递给后端的nginx服务器
                    proxy_set_header host $http_host;  #设置代理请求报文的host字段的值为变量$http_host的值
                    roxy_set_header X-Forward-For $remote_addr;  #将真实客户端的Ip送往后端服务器
            }
    
    
            error_page 404 /404.html;
                location = /40x.html {
            }
    
            error_page 500 502 503 504 /50x.html;
                location = /50x.html {
            }
        }
    }
    

    启动nginx服务:

    [root@nginx ~]# systemctl start nginx
    

    检查关闭firewalld和selinux:

    [root@nginx ~]# systemctl stop firewalld
    [root@nginx ~]# setenforce 0
    

    4、测试访问:

    测试访问wordpress 测试访问pma

    至此我们的nginx负载均衡环境已经搭建好了,下面我们来对wordpress和pma页面进行压测测试:

    [root@client ~]# ab -c 300 -n 100000 http://192.168.0.81/pma
    This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
    Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
    Licensed to The Apache Software Foundation, http://www.apache.org/
    
    Benchmarking 192.168.0.81 (be patient)
    Completed 10000 requests
    Completed 20000 requests
    Completed 30000 requests
    Completed 40000 requests
    Completed 50000 requests
    Completed 60000 requests
    Completed 70000 requests
    Completed 80000 requests
    Completed 90000 requests
    Completed 100000 requests
    Finished 100000 requests
    
    
    Server Software:        nginx/1.12.2
    Server Hostname:        192.168.0.81
    Server Port:            80
    
    Document Path:          /pma
    Document Length:        185 bytes
    
    Concurrency Level:      300
    Time taken for tests:   28.913 seconds
    Complete requests:      100000
    Failed requests:        0
    Write errors:           0
    Non-2xx responses:      100000
    Total transferred:      37900000 bytes
    HTML transferred:       18500000 bytes
    Requests per second:    3458.69 [#/sec] (mean)
    Time per request:       86.738 [ms] (mean)
    Time per request:       0.289 [ms] (mean, across all concurrent requests)
    Transfer rate:          1280.12 [Kbytes/sec] received
    
    Connection Times (ms)
                  min  mean[+/-sd] median   max
    Connect:        0   19 308.5      0   15039
    Processing:     1   56 675.1     34   25800
    Waiting:        0   55 675.1     34   25800
    Total:          1   75 810.8     34   28806
    
    Percentage of the requests served within a certain time (ms)
      50%     34
      66%     34
      75%     34
      80%     35
      90%     35
      95%     36
      98%     67
      99%   1034
     100%  28806 (longest request)
    

    从上面的结果看到client对blog和pma页面的访问速度大概急速每秒三千多个连接左右,那么接着我们来配置下缓存,然后再次做下压测对比下前后的情况。

    5、缓存配置

    在配置代理缓存前,首先需要确保服务器之间的时间是同步的:

    [root@nginx-gw ~]# ntpupdate ntp1.aliyun.com
    

    首先在nginx-gw上配置proxy-cache:

    #创建用于存放缓存的目录
    [root@nginx-gw ~]# mkdir /data/nginx/cache -pv
    mkdir: 已创建目录 "/data"
    mkdir: 已创建目录 "/data/nginx"
    mkdir: 已创建目录 "/data/nginx/cache"
    #接着编辑/etc/nginx/nginx.conf文件:
    [root@nginx-gw ~]# vim /etc/nginx/nginx.conf
    #在http上下文中添加下述命令
    proxy_cache_path  /data/nginx/cache/  levels=1:1 keys_zone=cache_zone:100m max_size=1g;
    
    #在server上下文中添加代理缓存的配置
        server {
            listen       80 default_server;
            listen       [::]:80 default_server;
            server_name  _;
            root         /usr/share/nginx/html;
    
            # Load configuration files for the default server block.
            include /etc/nginx/default.d/*.conf;
                   proxy_cache cache_zone ;
                   proxy_cache_key $request_uri;
                   proxy_cache_valid 200 302 301 1h;
                   proxy_cache_methods GET HEAD;
                   proxy_cache_valid any 1m;
                   add_header X-Cache '$upstream_cache_status from $host';
                   proxy_cache_use_stale http_502;
            location / {
                    proxy_set_header host $http_host;
                    proxy_set_header X-Forward-For $remote_addr;
                    proxy_pass http://webservers;
            }
            ....
    }
    

    再次进行压测:

    [root@client ~]# ab -c 300 -n 100000 http://192.168.0.81/blog
    This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
    Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
    Licensed to The Apache Software Foundation, http://www.apache.org/
    
    Benchmarking 192.168.0.81 (be patient)
    Completed 10000 requests
    Completed 20000 requests
    Completed 30000 requests
    Completed 40000 requests
    Completed 50000 requests
    Completed 60000 requests
    Completed 70000 requests
    Completed 80000 requests
    Completed 90000 requests
    Completed 100000 requests
    Finished 100000 requests
    
    
    Server Software:        nginx/1.12.2
    Server Hostname:        192.168.0.81
    Server Port:            80
    
    Document Path:          /blog
    Document Length:        185 bytes
    
    Concurrency Level:      300
    Time taken for tests:   13.917 seconds
    Complete requests:      100000
    Failed requests:        0
    Write errors:           0
    Non-2xx responses:      100000
    Total transferred:      41200000 bytes
    HTML transferred:       18500000 bytes
    Requests per second:    7185.23 [#/sec] (mean)
    Time per request:       41.752 [ms] (mean)
    Time per request:       0.139 [ms] (mean, across all concurrent requests)
    Transfer rate:          2890.93 [Kbytes/sec] received
    
    Connection Times (ms)
                  min  mean[+/-sd] median   max
    Connect:        0   19 168.1      0    7019
    Processing:     5   19  76.8     16   12837
    Waiting:        1   19  76.8     16   12837
    Total:          9   38 193.0     16   13838
    
    Percentage of the requests served within a certain time (ms)
      50%     16
      66%     17
      75%     17
      80%     17
      90%     18
      95%     20
      98%    134
      99%   1018
     100%  13838 (longest request)
    [root@client ~]# ab -c 300 -n 100000 http://192.168.0.81/pma
    This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
    Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
    Licensed to The Apache Software Foundation, http://www.apache.org/
    
    Benchmarking 192.168.0.81 (be patient)
    Completed 10000 requests
    Completed 20000 requests
    Completed 30000 requests
    Completed 40000 requests
    Completed 50000 requests
    Completed 60000 requests
    Completed 70000 requests
    Completed 80000 requests
    Completed 90000 requests
    Completed 100000 requests
    Finished 100000 requests
    
    
    Server Software:        nginx/1.12.2
    Server Hostname:        192.168.0.81
    Server Port:            80
    
    Document Path:          /pma
    Document Length:        185 bytes
    
    Concurrency Level:      300
    Time taken for tests:   13.149 seconds
    Complete requests:      100000
    Failed requests:        0
    Write errors:           0
    Non-2xx responses:      100000
    Total transferred:      41100000 bytes
    HTML transferred:       18500000 bytes
    Requests per second:    7605.36 [#/sec] (mean)
    Time per request:       39.446 [ms] (mean)
    Time per request:       0.131 [ms] (mean, across all concurrent requests)
    Transfer rate:          3052.54 [Kbytes/sec] received
    
    Connection Times (ms)
                  min  mean[+/-sd] median   max
    Connect:        0   18 158.8      0    7018
    Processing:     6   18  34.2     16    3238
    Waiting:        1   18  34.2     16    3238
    Total:         10   37 171.9     17    7036
    
    Percentage of the requests served within a certain time (ms)
      50%     17
      66%     17
      75%     17
      80%     17
      90%     19
      95%     22
      98%     49
      99%   1018
     100%   7036 (longest request)
    

    再次压测发现每秒的请求达到了7000多个,比没设置缓存前提升了1倍多,证明缓存有效。

    相关文章

      网友评论

        本文标题:nginx负载均衡+缓存实例

        本文链接:https://www.haomeiwen.com/subject/eddtjftx.html