VarnishでS3をオリジンとするキャッシュの構築
Varnish 4.0を使ってCentOS6.7(x64)に、S3をオリジンとしたキャッシュサーバーを設定した話。 S3に対してキャッシュ作らなくてもいいということもあるけど、オリジンはS3に限らず応用が効くのでそのときの手順をまとめてみました。
前提の環境
- CentOS6.7 (x64)
- Varnish 4.0.3
下準備
Varnishはjemallocを利用するため、下準備としてEPELのリポジトリを追加する。 また、Varnishもyumでインストールしたいのでリポジトリを追加。
# rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-4.0.el6.rpm # rpm --nosignature -i http://ftp-srv2.kddilabs.jp/Linux/distributions/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
インストール
jemallocとVarnishをインストールする。
# yum -y install --enablrepo=epel jemalloc インストール: jemalloc.x86_64 0:3.6.0-1.el6 完了しました!
# yum -y install --enablerepo=varnish-4.0 varnish ... インストール: varnish.x86_64 0:4.0.3-1.el6 依存性関連をインストールしました: varnish-libs.x86_64 0:4.0.3-1.el6
設定
待受ポートの変更
Varnishの待ち受けポートを変更する。
# /etc/sysconfig/varnish VARNISH_LISTEN_PORT=80
オリジンの設定
次にキャッシュするコンテンツが配置されているオリジンサーバに関する設定。 今回は、static web hosting が有効になっているS3をオリジンとする場合の設定をする。
オリジンのドメインは {your s3 bucket}.s3-website-ap-northeast-1.amazonaws.com
とする。
^/contents
へアクセスされた場合に、S3のオリジンサーバーへコンテンツを取りに行く設定をする。
(Varnishのキャッシュにヒットしなかった場合。)
# diff /etc/varnish/default.vcl /etc/varnish/default.vcl.org backend s3 { .host = "{your s3 bucket}.s3-website-ap-northeast-1.amazonaws.com"; .port = "80"; } sub vcl_recv { # Happens before we check if we have this in cache already. # # Typically you clean up the request here, removing cookies you don't need, # rewriting the request, etc. if (req.url ~ "^/contents/.*") { set req.http.host = "{your s3 bucket}.s3-website-ap-northeast-1.amazonaws.com"; set req.backend_hint = s3; } else { return (synth(403, "Forbidden!!")); } }
オリジンサーバーからのレスポンスで、S3に特有のヘッダーを削除してレスポンスをする設定。
sub vcl_backend_response { # Happens after we have read the response headers from the backend. # # Here you clean the response headers, removing silly Set-Cookie headers # and other mistakes your backend does. unset beresp.http.x-amz-id-2; unset beresp.http.x-amz-request-id; set beresp.ttl = 1w; }
設定ファイルが正しいか確認。
# varnishd -C -f /etc/varnish/default.vcl
起動
# /etc/init.d/varnish start Starting Varnish Cache: [ OK ] # /etc/init.d/varnishncsa start Starting varnish ncsa logging daemon: [ OK ] # /etc/init.d/varnishlog start Starting varnish logging daemon: [ OK ]
うまく設定できているか確認するために、s3のオリジンにあるコンテンツ {content}を取得する。
# curl -O http://{Your Varnish host}/contents/{content}
無事取得確認できたら、Cheome develop ment toolでも、同様のコンテンツを取得。
無事に、S3特有のヘッダーも削除されて、コンテンツも取得されていることがわかる。
というわけで、無事にS3をオリジンとするキャッシュサーバーが構築できたので、次はVarnishの設定パラメータを細かく見ていこうと思います。
それではm(__)m
参照
Using Varnish in front of your Amazon S3 static content - MDLog:/sysadmin