개발자의 노트
반응형

설정파일은 기본적으로 /etc/varnish/default.vcl 에 위치한다.


varnish의 캐쉬를 지우는 명령어는 ban이며, 

1. 로컬 서버에서만 curl 호출하여 캐쉬를 삭제할 수 있게 설정하는 법 (빨간색)

2. 웹브라우저에서 Shift + reload를 통해 캐쉬를 삭제할 수 있게 설정하는 법 (파란색)


우선 아래 설정파일을 참고하여 수정을 한다.


backend assets {

  .host = "127.0.0.1";

  .port = "80";

}


# ban

# curl -X BAN http://<VarnishServerIP:Port>/

# curl -X BAN http://<VarnishServerIP:Port>/static/images.png

acl ClearCache {

    "localhost";

    "127.0.0.1";

}


sub vcl_recv {


    if (req.request == "BAN") {

        if (!client.ip ~ ClearCache) {

            error 405 "Not allowed.";

        }


        # This option is to clear any cached object containing the req.url

        ban("req.url ~ "+req.url);


        # This option is to clear any cached object matches the exact req.url

        # ban("req.url == "+req.url);


        # This option is to clear any cached object containing the req.url 

        # AND matching the hostname.

        # ban("req.url ~ "+req.url+" && req.http.host == "+req.http.host);


        error 200 "Cached Cleared Successfully.";

    }


    # set client ip

    remove req.http.X-Forwarded-For;

    set req.http.X-Forwarded-For = req.http.rlnclientipaddr;          


    set req.backend = assets;


    # Allow purging of cache using shift + reload

    if (req.http.Cache-Control ~ "no-cache") {

        ban("req.url ~ "+req.url);

        error 200 "Cached Cleared Successfully.";

    }


    # Look for static media files in the cache (images, audio, ...) 

    if (req.url ~ "\.(css|gif|ico|jpg|jpeg|js|png|swf|txt)$") {

        unset req.http.cookie;        

        return(lookup);

    }


    # Do not cache any POST'ed data

    if (req.request == "POST") {

        return(pass);

    }


    # Do not cache any non-standard requests

    if (req.request != "GET" && req.request != "HEAD" &&

        req.request != "PUT" && req.request != "POST" &&

        req.request != "TRACE" && req.request != "OPTIONS" &&

        req.request != "DELETE") {

        return(pass);

    }


    return(lookup);

}


sub vcl_fetch {


    # Remove cookies and cache images for 24 hours

    if (req.url ~ "\.(css|gif|ico|jpg|jpeg|js|png|swf|txt)$") {

        unset beresp.http.Set-cookie;

        set beresp.ttl = 24h;

        return(deliver);

    }

 

    # Do not cache anything that does not return a value in the 200's

    if (beresp.status >= 300) {

        return(hit_for_pass);

    }

 

    # Do not cache content which varnish has marked uncachable

    if (beresp.ttl <= 0s) {

        return(hit_for_pass);

    }


    if (beresp.http.Cache-Control ~ "max-age") {

        unset beresp.http.Set-Cookie;

        return(deliver);

    }

 

    return(deliver);

}


sub vcl_hash {


    hash_data(req.url);

    if (req.http.host) {

        hash_data(req.http.host);

    } else {

        hash_data(server.ip);

    }

 

    # we do not want to always set the cookie in cache

    # (meaning this would be a per user cache)

    # see: https://www.varnish-cache.org/trac/wiki/VCLExampleCacheCookies

    #hash_data(req.http.cookie);;

 

    return (hash);

}



 

이제. varnishadm를 통해 varnish를 재시작하지않고 설정파일 적용하자.


# varnishadm -T localhost:6082


이때, Authentication required 가 발생하면 아래처럼.


# varnishadm -T localhost:6082 -S /etc/varnish/secret

200        

-----------------------------

Varnish Cache CLI 1.0

-----------------------------

Linux,3.4.76-65.111.amzn1.x86_64,x86_64,-sfile,-smalloc,-hcritbit

varnish-3.0.5 revision 1a89b1f


Type 'help' for command list.

Type 'quit' to close CLI session.


varnish> 


명령어


varnish> help

200        

help [command]

ping [timestamp]

auth response

quit

banner

status

start

stop

vcl.load <configname> <filename>

vcl.inline <configname> <quoted_VCLstring>

vcl.use <configname>

vcl.discard <configname>

vcl.list

vcl.show <configname>

param.show [-l] [<param>]

param.set <param> <value>

panic.show

panic.clear

storage.list

backend.list

backend.set_health matcher state

ban.url <regexp>

ban <field> <operator> <arg> [&& <field> <oper> <arg>]...

ban.list


설정파일을 default라는 이름으로 로드한다. (설정 이름은 맘대로)

이때 컴파일을 하면서 구문 오류 등을 체크해볼 수 있겠다.


varnish> vcl.load default /etc/varnish/default.vcl

200        

VCL compiled.


문제없이 로드되었다면 해당 default 설정 적용하자.


varnish> vcl.use default

200  


자, 이제 새로운 설정파일이 적용되었다. 


1. curl 호출하여 캐쉬를 삭제할 수 있게 설정하는 법은 아래와 같다.


varnishadm를 나와서 curl를 날려본다.


# curl -X BAN http://localhost:6081


<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

  <head>

    <title>200 Cached Cleared Successfully.</title>

  </head>

  <body>

    <h1>Error 200 Cached Cleared Successfully.</h1>

    <p>Cached Cleared Successfully.</p>

    <h3>Guru Meditation:</h3>

    <p>XID: 444139611</p>

    <hr>

    <p>Varnish cache server</p>

  </body>

</html>


이제 원하는 캐쉬를 삭제하였다. 


이때, 특정 경로나 특정 파일만 캐쉬를 삭제할 수도 있다.


# curl -X BAN http://localhost:6081/images/

# curl -X BAN http://localhost:6081/images/ping.png


2. 웹브라우저에서 Shift + reload를 통해 캐쉬를 삭제할 수 있게 설정하는 법은 


말 그대로 웹브라우저에서 Shift + Reload


참고: 로그를 보기 위해서는 # varnishlog

profile

개발자의 노트

@곽코딩

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!