Orjinal Döküman: http://www.netkolik.org/rehberler/varnish-cache-kurulumu-ve-wordpress-ayarlari.html
Varnish Cache web sunucunuz önünde çalışarak, önbelleğine aldığı dosyaları/sayfaları, bir daha web sunucunuza istek yapmadan kendi üzerinden kullanıcıya sunan bir önbellekleme sistemidir. Varnish cache hali hazırda kullanılan her türlü web sunucsu ile sorunsu olarak çalışan bir açık kaynak kodlu yazılımdır.
Varnish statik dosyalarınızı (html, css, jpg,png) önbelleklediği gibi, özellikle WordPress gibi dinamik içeriğe sahip sitelerinizi de önbellekleme kabiliyetine sahiptir. Asıl amacı sunucu kaynaklarını en verimli şekilde kullanmaya yöneliktir.
Yaptığım denemeler sonucu WordPress için en uygun ayarları Varnish 3.x sürümü ile elde ettim. Bu yazımda sizlere Varnish 3.x kurulumu ve WordPress için VCL ayarlarından bahsedeceğim.
VARNİSH 3 KURULUMU
CentOS 5/6, Debian 7/8 ve Ubuntu 12.04/14.04 için ayrı ayrı kurulum ve depo kaynakları olsa da, tüm ayarlamalar tüm işletim sistemleri için ortaktır.
Öncelikle kullandığınız işletim sistemine uygun olan paketi seçtiğinizdem emin olunuz.
CentOS 5.x
- rpm –nosignature -i https://repo.varnish-cache.org/redhat/varnish-3.0.el5.rpm
- yum install varnish
CentOS 6.x
- rpm –nosignature -i https://repo.varnish-cache.org/redhat/varnish-3.0.el6.rpm
- yum install varnish
Debian ve Ubuntu için /etc/apt/sources.list dosyasını düzenleyerek uygun olan repo kodunu en sona ekleyin.
- nano /etc/apt/sources.list
Debian 7.x
- deb http://repo.varnish-cache.org/debian/ wheezy varnish-3.0
Debian 8.x
- deb http://repo.varnish-cache.org/debian/ jessie varnish-3.0
Ubuntu 12.02
- deb http://repo.varnish-cache.org/ubuntu/ precise varnish-3.0
Ubuntu 14.04
- deb http://repo.varnish-cache.org/ubuntu/ trusty varnish-3.0
Debian ve Ubuntu için depo anahtarını ekleyip, depo listesini güncelleyip kurulumu yapalım.
- curl https://repo.varnish-cache.org/debian/GPG-key.txt | apt-key add –
- apt-get update
- apt-get install apt-transport-https varnish -y
Kurulum tamanlandığında aşağıdaki gibi bir mesaj göreceksiniz.
Setting up libvarnishapi1 (3.0.6-1~wheezy) ... Setting up manpages-dev (3.44-1) ... Setting up varnish (3.0.6-1~wheezy) ... Starting HTTP accelerator: varnishd. root@deneme:~#
VARNİSH DEFAULT VE DEFAULT.VCL AYARLARI
default dosyamızı düzenleyelim.
Debian ve Ubuntu için
- nano /etc/default/varnish
CentOS için
- nano /etc/sysconfig/varnish
İçerğini aşağıdaki gibi değiştirelim.
- # Configuration file for varnish
- #
- # /etc/init.d/varnish expects the variable $DAEMON_OPTS to be set from this
- # shell script fragment.
- #
- START=yes
- #
- # Maximum number of open files (for ulimit -n)
- NFILES=131072
- #
- # Locked shared memory (for ulimit -l)
- # Default log size is 82MB + header
- MEMLOCK=82000
- #
- # Maximum size of corefile (for ulimit -c). Default in Fedora is 0
- # DAEMON_COREFILE_LIMIT=”unlimited”
- #
- # Set this to 1 to make init script reload try to switch vcl without restart.
- # To make this work, you need to set the following variables
- # explicit: VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_ADDRESS,
- # VARNISH_ADMIN_LISTEN_PORT, VARNISH_SECRET_FILE
- RELOAD_VCL=1
- #
- ## Advanced configuration
- #
- # # Main configuration file.
- VARNISH_VCL_CONF=/etc/varnish/default.vcl
- #
- # # Default address and port to bind to
- # # Blank address means all IPv4 and IPv6 interfaces, otherwise specify
- # # a host name, an IPv4 dotted quad, or an IPv6 address in brackets.
- # VARNISH_LISTEN_ADDRESS=
- VARNISH_LISTEN_PORT=80
- #
- # # Telnet admin interface listen address and port
- VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
- VARNISH_ADMIN_LISTEN_PORT=6082
- #
- # # Shared secret file for admin interface
- VARNISH_SECRET_FILE=/etc/varnish/secret
- #
- # # The minimum number of worker threads to start
- VARNISH_MIN_THREADS=1
- #
- # # The Maximum number of worker threads to start
- VARNISH_MAX_THREADS=1000
- #
- # # Idle timeout for worker threads
- VARNISH_THREAD_TIMEOUT=120
- #
- # # Cache file location if using file cache
- #VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin
- #
- # # Cache size: in bytes, optionally using k / M / G / T suffix,
- # # or in percentage of available disk space using the % suffix.
- VARNISH_STORAGE_SIZE=1G
- #
- # # Backend storage specification
- # malloc runs from RAM, file from file
- VARNISH_STORAGE=“malloc,${VARNISH_STORAGE_SIZE}”
- #VARNISH_STORAGE=”file,${VARNISH_STORAGE_FILE},${VARNISH_STORAGE_SIZE}”
- #
- # # Default TTL used when the backend does not specify one
- VARNISH_TTL=120
- #
- # # DAEMON_OPTS is used by the init script. If you add or remove options,
- # # be sure you update this section, too.
- DAEMON_OPTS=”-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
- -f ${VARNISH_VCL_CONF} \
- -T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
- -t ${VARNISH_TTL} \
- -w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
- -u varnish -g varnish \
- -S ${VARNISH_SECRET_FILE} \
- -s ${VARNISH_STORAGE}”
- #
Burada Varnish 80 portunda çalışmasına ayarladık.
Şimdi de default.vcl dosyasını düzenleyelim. Bu düzenlemenin WordPress için özelleştirilmiş olduğunu, diğer çalışan sistemlerde sorun çıkarma ihtimalinin olduğunu belirtmek istiyorum.
Debian, Ubuntu ve CentOS için
- nano /etc/varnish/default.vcl
İçeriği aşağıdaki gibi değiştirin.
- backend origin {
- .host = “127.0.0.1”;
- .port = “8080”;
- .connect_timeout = 60s;
- .first_byte_timeout = 60s;
- .between_bytes_timeout = 60s;
- }
- #
- sub vcl_recv {
- # only using one backend
- set req.backend = origin;
- #
- # set standard proxied ip header for getting original remote address
- set req.http.X-Forwarded-For = client.ip;
- #
- # logged in users must always pass
- if( req.url ~ “^/wp-(login|admin)” || req.http.Cookie ~ “wordpress_logged_in_” ){
- return (pass);
- }
- # accept purges from w3tc and varnish http purge
- if (req.request == “PURGE”) {
- return (lookup);
- }
- #
- # don’t cache search results
- if( req.url ~ “\?s=” ){
- return (pass);
- }
- #
- # always pass through posted requests and those with basic auth
- if ( req.request == “POST” || req.http.Authorization ) {
- return (pass);
- }
- #
- # else ok to fetch a cached page
- unset req.http.Cookie;
- return (lookup);
- }
- #
- # accept purges from w3tc and varnish http purge
- sub vcl_hit {
- if (req.request == “PURGE”) { purge; }
- return (deliver);
- }
- #
- # accept purges from w3tc and varnish http purge
- sub vcl_miss {
- if (req.request == “PURGE”) { purge; }
- return (fetch);
- }
- #
- sub vcl_fetch {
- #
- # remove some headers we never want to see
- unset beresp.http.Server;
- unset beresp.http.X-Powered-By;
- #
- # only allow cookies to be set if we’re in admin area – i.e. commenters stay logged out
- if( beresp.http.Set-Cookie && req.url !~ “^/wp-(login|admin)” ){
- unset beresp.http.Set-Cookie;
- }
- #
- # don’t cache response to posted requests or those with basic auth
- if ( req.request == “POST” || req.http.Authorization ) {
- return (hit_for_pass);
- }
- #
- # only cache status ok
- if ( beresp.status != 200 ) {
- return (hit_for_pass);
- }
- #
- # don’t cache search results
- if( req.url ~ “\?s=” ){
- return (hit_for_pass);
- }
- #
- # else ok to cache the response
- set beresp.ttl = 24h;
- return (deliver);
- }
- #
- sub vcl_deliver {
- # add debugging headers, so we can see what’s cached
- if (obj.hits > 0) {
- set resp.http.X-Cache = “HIT”;
- }
- else {
- set resp.http.X-Cache = “MISS”;
- }
- # remove some headers added by varnish
- unset resp.http.Via;
- unset resp.http.X-Varnish;
- }
- #
- sub vcl_hash {
- hash_data( req.url );
- # altering hash so subdomains are ignored.
- # don’t do this if you actually run different sites on different subdomains
- if ( req.http.host ) {
- hash_data( regsub( req.http.host, “^([^\.]+\.)+([a-z]+)$”, “\1\2″ ) );
- } else {
- hash_data( server.ip );
- }
- # ensure separate cache for mobile clients (WPTouch workaround)
- if( req.http.User-Agent ~ “(iPod|iPhone|incognito|webmate|dream|CUPCAKE|WebOS|blackberry9\d\d\d)” ){
- hash_data(“touch”);
- }
- return (hash);
- }
default.vcl dosyasını düzenleyerek de, Varnish’in 80 portuna gelen istekleri alıp, arkaplanda 8080 portunda çalışan web sunucusuna iletmesini sağladık. Ayrıca WordPress için özelleştirilmiş olduğundan, WordPress siteniz üzerinde giriş yapmamış ziyaretçiler için web sunucunuz yerine Varnish üzerinden gösterim yapılacaktır. Üye girişi yapmış kullanıcılar ise Varnish cache sistemini atlayıp, onlar için websunucusu üzerinden gösterim yapılacaktır.
Şimdi ise websunucunuzun 80 portunu 8080 olarak değiştirmeye geldi. Bu düzenleme kullandığınız işletim sistemi, hosting paneli ve web sunucusuna göre değişiklik gösterdiğinden, kesin bir dosya yolu belirtemiyorum. Genel anlamı ile söylemek gerekirse Apache için httpd.confiçinde VirtualHost ayarlarını, Nginx için de nginx.conf içinde listen ayarını değiştirmeniz gerekiyor. Nano ile ayar dosyasını açtıktan sonra,
- server {
- listen 80;
- server_name netkolik.org
- <VirtualHost *:80>
- ServerAdmin webmaster@
kısmını
- server {
- listen 8080;
- server_name netkolik.org
- <VirtualHost *:8080>
- ServerAdmin webmaster@
olarak değiştirin.
Websuncusu ve Varnish yeniden başlatalım.
- service httpd restart – CentOS için (Apache)
- service apache2 restart – Debian/Ubuntu için (Apache)
- service nginx restart – Nginx için
- service varnish restart
Servisleri yeniden başlattıktan sonra Varnish 80 portunda Web sunucumuz 8080 portunda çalışır hale geldiler. Bu durumda Varnish 80 portuna gelen istekleri okuyup, eğer kendi bünyesinde önbelleğe aldı ise kendi üzerinden, eğer gelen istek önbellekte yok ise, 8080 portundaki web sunucusuna istekte bulunup, kendi önbelleğine alıp, aynı isteği diğer defa kendi önbelleğinden görüntüleyecektir.
VARNİSH CACHE İSTATİSTİKLERİ
SSH üzerinden varnishstat komutu ile Varnish istatistiklerini anlık olarak görüntüleyebilirsiniz.
- varnishstat
Karşınızda top komutuna benzer bir ekran görüntüsü çıkacaktır.
- 0+18:05:19
- Hitrate ratio: 6 6 6
- Hitrate avg: 0.9968 0.9968 0.9968
- 6972 0.00 0.11 client_conn – Client connections accepted
- 48089 0.00 0.74 client_req – Client requests received
- 44664 0.00 0.69 cache_hit – Cache hits
- 15 0.00 0.00 cache_hitpass – Cache hits for pass
- 862 0.00 0.01 cache_miss – Cache misses
Sol üstte görünen 0+18:05:19 ibaresi Varnish sunucumuzun 18 saat süre ile çalıştığını göstermektedir.
Hitrate ratio kısmı ise son 6 dakika içerisindeki Hitrate avg değerlerini vermektedir. 0.9968 değeri ise son 6 dakika içinde cache_miss/cache_hit değerlerinin oranıdır.
Sıralı şekilde görülen üç sütun ise; ilki toplam istek sayısı, anlık istek sayısı ve ratio oranlarıdır.
client_conn değeri, Varnish’in çalıştığı süre boyunca karşıladığı bağlantı sayısıdır.
client_req değeri, Varnish’in çalıştığı süre boyunca karşıladığı istek sayısıdır.
client_hit değeri, Varnish’in çalıştığı süre boyunca önbellekten gösterdiği istek sayısıdır.
client_hitpass değeri, Varnish’in çalıştığı süre boyunca doğrudan websunucusu üzerinden karşıladığı istek sayısıdır.
client_miss değeri, Varnish’in çalıştığı süre boyunca önbelleğe aldığı istek sayısıdır.
WORDPRESS İÇİN VARNİSH AYARLARI
WordPress için hali hazırda W3 Total Cache kullanıyorsanız, Varnish sunucunuzu tanıtarak, Cache üzerindeki Page Cache ayarlarınız değiştikçe, Varnish Cache önbelleğinin değişmesini de ayarlayabilirsiniz. Bunun için, WordPress admin menüsünden, Performance > General Settings >Varnish yolunu takip ederek, Varnish sunucu IP adresini W3 Total Cache ile uyumlu olması için ayarlayabilirsiniz.
W3 Total Cache içinde bu ayarı aktif ederek, Page Cache ayarları doğrultusunda Varnish Cache ayarlarıyla entegre çalışmasını sağladık. Purge cache seçeneğine tıklayarak da önbelleği kendimiz de temizleyebiliriz.
W3 Total Cache kullanmıyorsanız da Varnish HTTP Purge adlı eklenti ile de aynı işi gerçekleştirebilirsiniz. (https://wordpress.org/plugins/varnish-http-purge/)
default.vcl dosyamız, sadece WordPress ile uyumlu ayarlandığı için, çeşitli sitelerden sayfanızın header dosyasını görüntülediğinizde Varnish kullanılmıyor olarak gösterecektir.http://www.isvarnishworking.com/ adresinden sitenizi kontrol edebilirsiniz. Dosya özelleştirilmiş olduğundan Varnish header silinmiştir. Ama görebildiğiniz gibi Age ve X-Cache değişkenleri, Varnish’in çalıştığının göstergesidir.
Vary: Accept-Encoding X-CF-Powered-By: WP 1.3.16 X-Pingback: http://www.netkolik.org/xmlrpc.php Age: 7466 X-Cache: HIT Server: cloudflare-nginx
(default.vcl dosyamızda Varnish headeri yerine X-Cache değeri HIT olarak döndürülmektedir)
Varnish özelliklerini sunucunuzdan anlık olarak varnishstat vevarnishtop komutları ile gözlemleyebilirsiniz.