nginx负载均衡+缓存实例

背景介绍

背景拓扑

部署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倍多,证明缓存有效。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容

  • 一、前言 Nginx不光可以实现Web Server,还可以作为HTTP负载均衡来分发流量给后端的应用程序服务器,...
    小尛酒窝阅读 719评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • 1. Nginx的模块与工作原理 Nginx由内核和模块组成,其中,内核的设计非常微小和简洁,完成的工作也非常简单...
    rosekissyou阅读 10,211评论 5 124
  • Nginx是什么 没有听过Nginx?那么一定听过它的“同行”Apache吧!Nginx同Apache一样都是一种...
    老雷小朋友阅读 2,563评论 0 8
  • 渴望成功,害怕失败,是因为不想自己付出的努力功亏一篑。所有的彷徨,只为努力而祈祷。 ...
    大流芒阅读 325评论 0 2