4.使用Varnish加速Web
問題
通過配置Varnish緩存服務器,實現如下目標:
使用Varnish加速後端Apache Web服務
使用varnishadm管理緩存頁面
使用varnishstat查看Varnish狀態
方案
通過源碼編譯安裝Varnish緩存服務器
編譯安裝Varnish軟件
複製啓動腳本與配置文件
修改配置文件,緩存代理源Web服務器,實現Web加速功能
使用3臺RHEL6虛擬機,其中一臺作爲Web服務器(192.168.4.205)、一臺作爲Varnish代理服務器(192.168.4.5),另外一臺作爲測試用的Linux客戶機(192.168.4.100),如圖-6所示。
圖-6
對於Web服務器的部署,此實驗中僅需要安裝httpd軟件、啓動服務,並生成測試首頁文件即可,默認httpd網站根路徑爲/var/www/html,首頁文檔名稱爲index.html。
步驟
實現此案例需要按照如下步驟進行。
步驟一:構建Web服務器
1)使用yum安裝web軟件包
[root@pc205 ~]# yum -y install httpd
… …
[root@pc205 ~]# rpm -q httpd
httpd-2.2.15-29.el6_4.x86_64
2)啓用httpd服務,並設爲開機自動運行
[root@pc205 ~]# service httpd restart ; chkconfig httpd on
Stopping httpd: [FAILED]
Starting httpd: [OK]
httpd服務默認通過TCP 80端口監聽客戶端請求:
[root@pc205 ~]# netstat -anptu | grep httpd
tcp 0 0 :::80 ::? LISTEN 2813/httpd
3)爲Web訪問建立測試文件
在網站根目錄/var/www/html下創建一個名爲index.html的首頁文件:
[root@pc205 ~]# cat /var/www/html/index.html
Welcome
hello
hello
步驟二:部署Varnish緩存服務器
1)編譯安裝軟件
[root@svr5 ~]# yum -y install readline-devel pcre-devel //安裝軟件依賴包
[root@svr5 ~]# useradd -s /sbin/nologin varnish //創建賬戶
[root@svr5 ~]# tar -xzf varnish-3.0.6.tar.gz
[root@svr5 ~]# cd varnish-3.0.6
[root@svr5 varnish-3.0.6]# ./configure --prefix=/usr/local/varnish
[root@svr5 varnish-3.0.6]# make && make install
2)複製啓動腳本及配置文件
[root@svr5 varnish-3.0.6]# cp redhat/varnish.initrc /etc/init.d/varnish
[root@svr5 varnish-3.0.6]# cp redhat/varnish.sysconfig /etc/sysconfig/varnish
[root@svr5 varnish-3.0.6]# cp redhat/varnish_reload_vcl /usr/bin/
[root@svr5 varnish-3.0.6]# ln -s /usr/local/varnish/sbin/varnishd /usr/sbin/
3)修改Varnish文件
[root@svr5 ~]# vim /etc/sysconfig/varnish
VARNISH_VCL_CONF=/etc/varnish/default.vcl #vcl文件路徑
VARNISH_LISTEN_PORT=80 #默認端口
VARNISH_SECRET_FILE=/etc/varnish/secret #密鑰文件
VARNISH_STORAGE_SIZE=64M #緩存大小
VARNISH_STORAGE="malloc,${VARNISH_STORAGE_SIZE}" #基於內存方式
4)修改代理配置文件
[root@svr5 ~]# mkdir /etc/varnish
[root@svr5 ~]# cp /usr/local/varnish/etc/default.vcl /etc/varnish/
[root@svr5 ~]# uuidgen > /etc/varnish/secret
[root@svr5 ~]# vim /etc/varnish/default.vcl
backend default {
.host = "192.168.4.205";
.port = "80";
}
[root@svr5 ~]# service varnish start
步驟三:客戶端測試
1)通過/etc/hosts文件,配置域名解析,將域名解析爲Squid服務器IP地址
[root@client ~]# cat /etc/hosts
.. ..
192.168.4.5 www.tarena.com
2)客戶端開啓瀏覽器,分別訪問兩個不同的域名站點
[root@client ~]# firefox http://www.tarena.com