腾讯云国际站代理商:‌如何搭建Varnish缓存服务器?

简介:TG@luotuoemo

本文由腾讯云代理商【聚搜云】撰写

1. 安装Varnish

  • 在Ubuntu 22.04系统上

    1. 添加Varnish的APT源:

      bash

      curl -fsSL https://packagecloud.io/varnishcache/varnish70/gpgkey | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/varnish.gpg
      echo "deb https://packagecloud.io/varnishcache/varnish70/ubuntu/ focal main" | sudo tee /etc/apt/sources.list.d/varnishcache_varnish70.list
      echo "deb-src https://packagecloud.io/varnishcache/varnish70/ubuntu/ focal main" | sudo tee -a /etc/apt/sources.list.d/varnishcache_varnish70.list
      
    2. 更新包列表并安装Varnish:

      bash

      sudo apt update
      sudo apt install varnish
      
  • 在CentOS 7系统上

    1. 添加Varnish的YUM源:

      bash

      curl -s https://packagecloud.io/install/repositories/varnishcache/varnish60lts/script.rpm.sh | sudo bash
      
    2. 安装Varnish:

      bash

      sudo yum install varnish
      

2. 配置Varnish

  • 编辑Varnish配置文件

    bash

    sudo nano /etc/varnish/default.vcl
    
  • 配置后端服务器

    vcl

    backend default {
        .host = "127.0.0.1";
        .port = "8080";
    }
    
    • 127.0.0.18080替换为您的后端服务器IP和端口。
  • 配置缓存规则

    vcl

    sub vcl_recv {
        if (req.method == "GET") {
            return (hash);
        }
        if (req.url ~ ".(png|jpg|jpeg|gif|css|js)$") {
            return (hash);
        }
    }
    
    • 这将告诉Varnish缓存静态文件。

3. 启动Varnish

  • 启动Varnish服务

    bash

    sudo systemctl start varnish
    
  • 设置Varnish开机自启

    bash

    sudo systemctl enable varnish
    

4. 配置Web服务器

  • 对于Apache

    1. 修改Apache配置文件,将监听端口改为8080:

      apache

      Listen 8080
      
    2. 重启Apache服务:

      bash

      sudo systemctl restart apache2
      
  • 对于Nginx

    1. 修改Nginx配置文件,将监听端口改为8080:

      nginx

      server {
          listen 8080;
          ...
      }
      
    2. 重启Nginx服务:

      bash

      sudo systemctl restart nginx
      

5. 验证Varnish

  • 在浏览器中访问您的网站,检查Varnish是否正常工作。您可以通过查看HTTP响应头来确认:

    curl -I http://your_domain.com

    • 如果Varnish正常工作,您应该看到类似以下的响应头:

      X-Varnish: 12345
      Age: 0
      Via: 1.1 varnish (Varnish/7.0)