一:使用Varnish加速Web
通过配置Varnish缓存服务器,实现如下目标:
- 使用Varnish加速后端Web服务
- 代理服务器可以将远程的Web服务器页面缓存在本地
- 远程Web服务器对客户端用户是透明的
- 利用缓存机制提高网站的响应速度
- 使用varnishadm命令管理缓存页面
- 使用varnishstat命令查看Varnish状态
方案
通过源码编译安装Varnish缓存服务器
- 编译安装Varnish软件
修改配置文件,缓存代理源Web服务器,实现Web加速功能
使用3台RHEL7虚拟机,其中一台作为Web服务器(192.168.2.100)、一台作为Varnish代理服务器(192.168.4.5,192.168.2.5),另外一台作为测试用的Linux客户机(192.168.4.10)
对于Web服务器的部署,此实验中仅需要安装nginx或者httpd软件、启动服务,并生成测试首页文件即可,默认httpd网站根路径为/var/www/html,首页文档名称为index.html,默认nginx网站根路径为/usr/local/nginx/html,默认首页为index.html。下面的实验我们以httpd为例作为Web服务器。
步骤一:构建Web服务器
1)使用yum安装web软件包
1 [root@web1 ~]# yum -y install httpd
2)启用httpd服务(注意需要关闭nginx,否则端口冲突)
1 [root@web1 ~]# systemctl start httpd 2 httpd服务默认通过TCP 80端口监听客户端请求: 3 [root@web1 ~]# netstat -anptu | grep httpd 4 tcp 0 0 :::80 :::* LISTEN 2813/httpd
3)为Web访问建立测试文件
在网站根目录/var/www/html下创建一个名为index.html的首页文件:
1 [root@web1 ~]# cat /var/www/html/index.html 2 192.168.2.100
4)测试页面是否正常(代理服务器测试后台web)
1 [root@proxy ~]# firefox http://192.168.2.100
步骤二:部署Varnish缓存服务器(192.168.4.5)
1)编译安装软件
1 [root@proxy ~]# yum -y install gcc readline-devel //安装软件依赖包 2 [root@proxy ~]# yum -y install ncurses-devel //安装软件依赖包 3 [root@proxy ~]# yum -y install pcre-devel //安装软件依赖包 4 [root@proxy ~]# yum -y install python-docutils //安装软件依赖包 5 [root@proxy ~]# useradd -s /sbin/nologin varnish //创建账户 6 [root@proxy ~]# tar -xf varnish-5.2.1.tar.gz 7 [root@proxy ~]# cd varnish-5.2.1 8 [root@proxy varnish-5.2.1]# ./configure 9 [root@proxy varnish-5.2.1]# make && make install
2)复制配置文件(注意相对路径与绝对路径)
1 [root@proxy varnish-5.2.1]# cp etc/example.vcl /usr/local/etc/default.vcl
3)修改代理配置文件
1 [root@proxy ~]# vim /usr/local/etc/default.vcl 2 backend default { 3 .host = "192.168.2.100"; 4 .port = "80"; 5 }
4)启动服务
1 [root@proxy ~]# varnishd -f /usr/local/etc/default.vcl 2 //varnishd命令的其他选项说明如下: 3 //varnishd -s malloc,128M 定义varnish使用内存作为缓存,空间为128M 4 //varnishd -s file,/var/lib/varnish_storage.bin,1G 定义varnish使用文件作为缓存
步骤三:客户端测试
1)客户端开启浏览器访问
1 [root@client ~]# curl http://192.168.4.5
步骤四:其他操作
1)查看varnish日志
1 [root@proxy ~]# varnishlog //varnish日志 2 [root@proxy ~]# varnishncsa //访问日志
2)更新缓存数据,在后台web服务器更新页面内容后,用户访问代理服务器看到的还是之前的数据,说明缓存中的数据过期了需要更新(默认也会自动更新,但非实时更新)。
1 [root@proxy ~]# varnishadm 2 varnish> ban req.url ~ .* 3 //清空缓存数据,支持正则表达式
浙公网安备 33010602011771号