免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4595 | 回复: 3
打印 上一主题 下一主题

CentOS 5.5环境下安装配置Varnish [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-12 10:53 |只看该作者 |倒序浏览
#======================= Varnish安装 =========================#

如果是RedHat/CentOS系统,在安装varnish的时候首先要安装以下软件包
automake
autoconf
libtool
ncurses-devel
libxslt
groff
pcre-devel
pkgconfig
  1. groupadd www
  2. useradd www -g www -s /sbin/nologin
  3. mkdir -p /data/varnish/{cache,logs}
  4. chmod +w /data/varnish/{cache,logs}
  5. chown -R www:www /data/varnish/{cache,logs}
  6. cd /opt
  7. yum install -y automake autoconf libtool ncurses-devel libxslt groff pcre-devel pkgconfig
  8. wget http://sourceforge.net/projects/varnish/files/varnish/2.1.3/varnish-2.1.3.tar.gz/download
  9. tar -zxvf varnish-2.1.3.tar.gz
  10. cd varnish-2.1.3
  11. ./configure --prefix=/usr/local/varnish
  12. make;make install
复制代码
#====================== varnish配置 ========================#
  1. vi /usr/local/varnish/etc/varnish/kerry.vcl
复制代码
  1. backend kerry {              #定义后端服务器名
  2.   .host = "192.168.9.203";    #定义后端服务器IP
  3.   .port = "80";      #定义后端服务器端口
  4. }

  5. backend king {
  6.   .host = "192.168.9.204";
  7.   .port = "80";
  8. }

  9. #定义访问控制列表,充许那些IP清除varnish 缓存
  10. acl local {
  11.   "localhost";
  12.   "127.0.0.1";
  13. }

  14. #判断host请求针对那个后端服务器
  15. sub vcl_recv {
  16.   if (req.http.host ~ "^(www.)?kerry.com$") {  #泛域名的写法"^(.*.)?kerry.com$"
  17.    set req.backend = kerry;
  18.   }
  19.   elsif (req.http.host ~ "^(www.)?king.com$") {
  20.    set req.backend = king;
  21.   }
  22.   else {
  23.    error 404 "Unknown HostName!"; #如果都不匹配,返回404错误
  24.   }
  25. #不充许非访问控制列表的IP进行varnish缓存清除
  26.   if(req.request == "PURGE") {
  27.    if (!client.ip ~ local) {
  28.     error 405 "Not Allowed.";
  29.     return (lookup);
  30.     }
  31.   }
  32.   #清除url中有jpg|png|gif等文件的cookie
  33.   if (req.request == "GET" && req.url ~ "\.(jpg|png|gif|swf|jpeg|ico)$") {
  34.    unset req.http.cookie;
  35.   }
  36.   #取消服务器上images目录下所有文件的cookie
  37.   if (req.url ~ "^/images") {
  38.    unset req.http.cookie;
  39.   }
  40.   #判断req.http.X-Forwarded-For,如果前端有多重反向代理,这样可以获取客户端IP地址。
  41.   if (req.http.x-forwarded-for) {
  42.    set req.http.X-Forwarded-For =
  43.    req.http.X-Forwarded-For ", " client.ip;
  44.   }
  45.   else {
  46.    set req.http.X-Forwarded-For = client.ip;
  47.   }
  48.   if (req.request != "GET" &&
  49.       req.request != "HEAD" &&
  50.       req.request != "PUT" &&
  51.       req.request != "POST" &&
  52.       req.request != "TRACE" &&
  53.       req.request != "OPTIONS" &&
  54.       req.request != "DELETE") {
  55.    return (pipe);
  56.   }
  57.   #针对请求和url地址判断,是否在varnish缓存里查找
  58.   if (req.request != "GET" && req.request != "HEAD") {
  59.    return (pass);
  60.   } ## 对非GET|HEAD请求的直接转发给后端服务器
  61.   if (req.http.Authorization || req.http.Cookie) {
  62.    return (pass);
  63.   }
  64.   if (req.request == "GET" && req.url ~ "\.(php)($|\?)") {
  65.    return (pass);
  66.    } #对GET请求,且url里以.php和.php?结尾的,直接转发给后端服务器
  67.        return (lookup);
  68.   }  #除了以上的访问以外,都在varnish缓存里查找

  69. sub vcl_pipe {
  70.   return (pipe);
  71. }

  72. sub vcl_pass {
  73.   return (pass);
  74. }

  75. sub vcl_hash {
  76.   set req.hash += req.url;
  77.   if (req.http.host) {
  78.    set req.hash += req.http.host;
  79.   } else {
  80.    set req.hash += server.ip;
  81.   }
  82.   return (hash);
  83. }

  84. sub vcl_hit {
  85.   if (!obj.cacheable) {
  86.    return (pass);
  87.   }
  88.   if (req.request == "PURGE") {
  89.           set obj.ttl = 0s;
  90.           error 200 "Purged.";
  91.        }
  92.   return (deliver);
  93. }

  94. sub vcl_miss {
  95.   return (fetch);
  96. }

  97. sub vcl_fetch {
  98.   if (!beresp.cacheable) {
  99.    return (pass);
  100.   }
  101.   if (beresp.http.Set-Cookie) {
  102.    return (pass);
  103.   }
  104.   #WEB服务器指明不缓存的内容,varnish服务器不缓存
  105.   if (beresp.http.Pragma ~ "no-cache" ||
  106.       beresp.http.Cache-Control ~ "no-cache" ||
  107.              beresp.http.Cache-Control ~ "private") {
  108.    return (pass);
  109.        }
  110.        #对.txt .js .shtml结尾的URL缓存时间设置1小时,对其他的URL缓存时间设置为10天
  111.   if (req.request == "GET" && req.url ~ "\.(txt|js|css|shtml|html|htm)$") {
  112.                 set beresp.ttl = 3600s;
  113.   }
  114.   else {
  115.                 set beresp.ttl = 10d;
  116.   }
  117.   return (deliver);
  118. }
  119. #添加在页面head头信息中查看缓存命中情况
  120. sub vcl_deliver {
  121.   set resp.http.x-hits = obj.hits ;
  122.   if (obj.hits > 0) {
  123.    set resp.http.X-Cache = "HIT cqtel-bbs";
  124.   }
  125.   else {
  126.        set resp.http.X-Cache = "MISS cqtel-bbs";
  127.   }
  128. }

  129. sub vcl_error {
  130.   set obj.http.Content-Type = "text/html; charset=utf-8";
  131.   synthetic {"
  132. <?xml version="1.0" encoding="utf-8"?>
  133. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  134. <html>
  135.     <head>
  136.        <title>"} obj.status " " obj.response {"</title>
  137.     </head>
  138.     <body>
  139.        <h1>Error "} obj.status " " obj.response {"</h1>
  140.        <p>"} obj.response {"</p>
  141.        <h3>Guru Meditation:</h3>
  142.        <p>XID: "} req.xid {"</p>
  143.        <hr>
  144.        <address>
  145.           <a href="http://www.bbs.com/">bbs cache server</a>
  146.        </address>
  147.     </body>
  148. </html>
  149. "};
  150.   return (deliver);
  151. }
复制代码
注意:在2.1后的版本里,原"obj.*"的变量全部变为"beresp.*"了,需要留意一下

启动varnish
  1. /usr/local/varnish/sbin/varnishd -u www -g www -f /usr/local/varnish/etc/varnish/kerry.vcl -a 192.168.9.201:80 -s file,/data/varnish/cache/varnish_cache.data,1G -w 1024,51200,10 -t 3600 -T 192.168.9.201:3000
复制代码
  1. echo "/usr/local/varnish/sbin/varnishd -u www -g www -f /usr/local/varnish/etc/varnish/kerry.vcl -a 192.168.9.201:80 -s file,/data/varnish/cache/varnish_cache.data,1G -w 1024,51200,10 -t 3600 -T 192.168.9.201:3000" >> /etc/rc.local
复制代码
参数:
-u 以什么用运行
-g 以什么组运行
-f varnish配置文件
-a 绑定IP和端口
-s varnish缓存文件位置与大小
-w 最小,最大线程和超时时间
-T varnish管理端口,主要用来清除缓存
-p client_http11=on 支持http1.1协议
-P(大P) /usr/local/varnish/var/varnish.pid 指定其进程码文件的位置,实现管理

停止varnish
pkill varnishd  #结束varnishd进程

启动日志,方便分析网站访问情况
  1. /usr/local/varnish/bin/varnishncsa -w /data/varnish/logs/varnish.log &
复制代码
  1. echo "/usr/local/varnish/bin/varnishncsa -w /data/varnish/logs/varnish.log &" >> /etc/rc.local
复制代码
参数: -w 指定varnish访问日志要写入的目录与文件

varnish日志切割
  1. vi /root/cut_varnish_log.sh
复制代码
  1. #!/bin/sh
  2. logs_path=/data/varnish/logs
  3. vlog=${logs_path}/varnish.log
  4. date=$(date -d "yesterday" +"%Y-%m-%d")
  5. pkill -9 varnishncsa
  6. mkdir -p ${logs_path}/$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
  7. mv /data/varnish/logs/varnish.log ${logs_path}/$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/varnish-${date}.log
复制代码
  1. /usr/local/varnish/bin/varnishncsa -w /data/varnish/logs/varnish.log &
复制代码
使用计划任务,每天晚上凌晨00点运行日志切割脚本
  1. echo "0 0 * * * /root/cut_varnish_log.sh" >> /etc/crontab
复制代码
  1. cat /etc/rc.local
复制代码
  1. ulimit -SHn 51200
  2. /usr/local/varnish/sbin/varnishd -u www -g www -f /usr/local/varnish/etc/varnish/kerry.vcl -a 192.168.9.201:80 -s file,/data/varnish/cache/varnish_cache.data,1G -w 1024,51200,10 -t 3600 -T 192.168.9.201:3000
  3. /usr/local/varnish/bin/varnishncsa -w /data/varnish/logs/varnish.log &
复制代码
#======================== Varnish 缓存清除 ====================#
  1. /usr/local/varnish/bin/varnishadm -T 192.168.9.201:3000 purge "req.http.host ~ www.kerry.com$ && req.url ~ /static/image/tp.php"
复制代码
说明:
192.168.9.201:3000 为被清除缓存服务器地址
www.kerry.com 为被清除的域名
/static/image/tp.php 为被清除的url地址列表

清除所有缓存
  1. /usr/local/varnish/bin/varnishadm -T 192.168.9.201:3000 url.purge *$
复制代码
清除image目录下所有缓存
  1. /usr/local/varnish/bin/varnishadm -T 192.168.9.201:3000 url.purge /image/
复制代码
查看Varnish服务器连接数与命中率
  1. /usr/local/varnish/bin/varnishstat –n /data/varnish/cache/varnish_cache.data
复制代码
#======================= 内核优化 =========================#
  1. vi /etc/sysctl.conf
复制代码
  1. net.ipv4.tcp_syncookies = 1
  2. net.ipv4.tcp_tw_reuse = 1
  3. net.ipv4.tcp_tw_recycle = 1
  4. #net.ipv4.tcp_fin_timeout = 30
  5. #net.ipv4.tcp_keepalive_time = 300
  6. net.ipv4.ip_local_port_range = 1024 65000
  7. net.ipv4.tcp_max_syn_backlog = 8192
  8. net.ipv4.tcp_max_tw_buckets = 5000

  9. net.ipv4.tcp_max_syn_backlog = 65536
  10. net.core.netdev_max_backlog =  32768
  11. net.core.somaxconn = 32768

  12. net.core.wmem_default = 8388608
  13. net.core.rmem_default = 8388608
  14. net.core.rmem_max = 16777216
  15. net.core.wmem_max = 16777216

  16. net.ipv4.tcp_timestamps = 0
  17. net.ipv4.tcp_synack_retries = 2
  18. net.ipv4.tcp_syn_retries = 2

  19. net.ipv4.tcp_tw_recycle = 1
  20. #net.ipv4.tcp_tw_len = 1
  21. net.ipv4.tcp_tw_reuse = 1

  22. net.ipv4.tcp_mem = 94500000 915000000 927000000
  23. net.ipv4.tcp_max_orphans = 327680
复制代码
0
  1. /sbin/sysctl -p
复制代码
#=================== Varnish添加到服务自启动 ====================#
配置启动文件
  1. vi /etc/init.d/varnish
复制代码
  1. #! /bin/sh
  2. #
  3. # varnish Control the varnish HTTP accelerator
  4. #
  5. # chkconfig: - 90 10
  6. # description: Varnish is a high-perfomance HTTP accelerator
  7. # processname: varnishd
  8. # config: /etc/sysconfig/varnish
  9. # pidfile: /var/run/varnish/varnishd.pid

  10. ### BEGIN INIT INFO
  11. # Provides: varnish
  12. # Required-Start: $network $local_fs $remote_fs
  13. # Required-Stop: $network $local_fs $remote_fs
  14. # Should-Start: $syslog
  15. # Short-Description: start and stop varnishd
  16. # Description: Varnish is a high-perfomance HTTP accelerator
  17. ### END INIT INFO

  18. # Source function library.
  19. . /etc/init.d/functions

  20. retval=0
  21. pidfile=/var/run/varnish.pid

  22. exec="/usr/local/varnish/sbin/varnishd"
  23. prog="varnishd"
  24. config="/usr/local/varnish/etc/varnish/varnish"
  25. lockfile="/var/lock/subsys/varnish"

  26. # Include varnish defaults
  27. [ -e /usr/local/varnish/etc/varnish/varnish ] && . /usr/local/varnish/etc/varnish/varnish


  28. start() {

  29.     if [ ! -x $exec ]
  30.      then
  31.          echo $exec not found
  32.          exit 5
  33.      fi

  34.     if [ ! -f $config ]
  35.      then
  36.          echo $config not found
  37.          exit 6
  38.      fi
  39.      echo -n "Starting varnish HTTP accelerator: "

  40.     # Open files (usually 1024, which is way too small for varnish)
  41.      ulimit -n ${NFILES:-131072}

  42.     # Varnish wants to lock shared memory log in memory.
  43.     ulimit -l ${MEMLOCK:-82000}

  44.         # $DAEMON_OPTS is set in /etc/sysconfig/varnish. At least, one
  45.          # has to set up a backend, or /tmp will be used, which is a bad idea.
  46.      if [ "$DAEMON_OPTS" = "" ]; then
  47.          echo "\$DAEMON_OPTS empty."
  48.          echo -n "Please put configuration options in $config"
  49.          return 6
  50.      else
  51.          # Varnish always gives output on STDOUT
  52.          daemon   $exec -P $pidfile "$DAEMON_OPTS" > /dev/null 2>&1
  53.          retval=$?
  54.          if [ $retval -eq 0 ]
  55.          then
  56.              touch $lockfile
  57.              echo_success
  58.              echo
  59.          else
  60.              echo_failure
  61.          fi
  62.          return $retval
  63.      fi
  64. }

  65. stop() {
  66.      echo -n "Stopping varnish HTTP accelerator: "
  67.      killproc $prog
  68.      retval=$?
  69.      echo
  70.      [ $retval -eq 0 ] && rm -f $lockfile
  71.      return $retval
  72. }

  73. restart() {
  74.      stop
  75.      start
  76. }

  77. reload() {
  78.      restart
  79. }

  80. force_reload() {
  81.      restart
  82. }

  83. rh_status() {
  84.      status $prog
  85. }

  86. rh_status_q() {
  87.      rh_status >/dev/null 2>&1
  88. }

  89. # See how we were called.
  90. case "$1" in
  91.      start)
  92.          rh_status_q && exit 0
  93.          $1
  94.          ;;
  95.      stop)
  96.          rh_status_q || exit 0
  97.          $1
  98.          ;;
  99.      restart)
  100.          $1
  101.          ;;
  102.      reload)
  103.          rh_status_q || exit 7
  104.          $1
  105.          ;;
  106.      force-reload)
  107.          force_reload
  108.          ;;
  109.      status)
  110.          rh_status
  111.          ;;
  112.      condrestart|try-restart)
  113.          rh_status_q || exit 0
  114.          restart
  115.          ;;
  116.      *)
  117.      echo "Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"

  118.     exit 2
  119. esac

  120. exit $?
复制代码
varnish的配置调用文件,是用来告诉程序从哪里读取配置文件,启动参数有哪些等
  1. vi /usr/local/varnish/etc/varnish
复制代码
  1. # Configuration file for varnish
  2. #
  3. # /etc/init.d/varnish expects the variable $DAEMON_OPTS to be set from this
  4. # shell script fragment.
  5. #

  6. # Maximum number of open files (for ulimit -n)
  7. NFILES=131072

  8. # Locked shared memory (for ulimit -l)
  9. # Default log size is 82MB + header
  10. MEMLOCK=1000000

  11. ## Alternative 2, Configuration with VCL
  12. DAEMON_OPTS="-a 192.168.9.201:80 \
  13.               -f /usr/local/varnish/etc/varnish/kerry.vcl \
  14.               -T 192.168.9.201:3000 \
  15.               -u www -g www \
  16.               -n /data/varnish/cache \
  17.               -s file,/data/varnish/cache/varnish_cache.data,1G"
复制代码
添加到系统服务,开机自启动
  1. chmod +x /etc/init.d/varnish
  2. /sbin/chkconfig --add varnish
  3. /sbin/chkconfig --level 2345 varnish on
复制代码
开启varnish
  1. /etc/init.d/varnish start
复制代码
关闭varnish
  1. /etc/init.d/varnish stop
复制代码

论坛徽章:
0
2 [报告]
发表于 2013-01-30 10:33 |只看该作者
这么好的教程,竟然没人顶,太不人道了,顶起……

论坛徽章:
224
2022北京冬奥会纪念版徽章
日期:2015-08-10 16:30:32操作系统版块每日发帖之星
日期:2016-02-18 06:20:00操作系统版块每日发帖之星
日期:2016-03-01 06:20:00操作系统版块每日发帖之星
日期:2016-03-02 06:20:0015-16赛季CBA联赛之上海
日期:2019-09-20 12:29:3219周年集字徽章-周
日期:2019-10-01 20:47:4815-16赛季CBA联赛之八一
日期:2020-10-23 18:30:5320周年集字徽章-20	
日期:2020-10-28 14:14:2615-16赛季CBA联赛之广夏
日期:2023-02-25 16:26:26CU十四周年纪念徽章
日期:2023-04-13 12:23:1015-16赛季CBA联赛之四川
日期:2023-07-25 16:53:45操作系统版块每日发帖之星
日期:2016-05-10 19:22:58
3 [报告]
发表于 2013-01-30 11:35 |只看该作者
看看这个
  1. apt-cache search varnish
  2. libvarnishapi-dev - development files for Varnish
  3. libvarnishapi1 - shared libraries for Varnish
  4. varnish - state of the art, high-performance web accelerator
  5. varnish-dbg - debugging symbols for varnish
  6. varnish-doc - documentation for Varnish Cache
复制代码

论坛徽章:
0
4 [报告]
发表于 2013-06-24 14:45 |只看该作者
本帖最后由 心若寒江雪 于 2013-06-24 14:52 编辑

你好,我安装的是varnish-3.0.3 我使用varnishstat命令查看命中率的时候却发现如下情景(程序已经运行一段时间了):

我是通过/usr/local/varnish/sbin/varnishd -n /data/varnish/cache -f /etc/varnish/default.vcl \
-a 0.0.0.0:80 -s file,/data/varnish/cache/varnish_cache.data,1G -g nginx -u nginx
这样的方式启动的

之后我索性直接启动发现却可以了。不知道为什么。

回复 1# king_819


   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP