侧边栏壁纸
博主头像
nivnek博主等级

道阻且长,行则将至

  • 累计撰写 21 篇文章
  • 累计创建 27 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Deploy Varnish in Kubernetes

kenvin
2022-10-25 / 0 评论 / 2 点赞 / 1998 阅读 / 7947 字

What is Varnish?

Varnish is a layer of HTTP cache that caches requests mostly for anonymous users before they hit an application layer. Typically Varnish cache is stored in RAM, which helps to achieve higher performance. If all available memory is used for cache, the last used cache items will be purged.

Varnish vcl config

You will need to provide your custom vcl file, you can put this in a configmap the following way.

kubectl create configmap varnish-vcl --from-file=varnish.vcl

A very simple vcl example config file, here it wil take the request hostname and transfer it to a backend, in the backend we define the Kubernetes service name. No need for multiple backend, because Kubernetes does the load balancing if there are multiple pods defined.

vcl 4.0;

import directors;
import std;


backend app1 {
        .host = "servcie1";
        .port = "8080";

}

backend app2 {
        .host = "service2";
        .port = "8080";
}
sub vcl_recv {
    #cache not HTTP GET and HEAD method request
    if(req.url ~ "(?i)/api") {
    if(req.method !="GET" && req.method !="HEAD") {
      set req.backend_hint = service1;
      return(pass); 
      } else {
    set req.backend_hint = service1;
    return(hash);
    }
    }
}

sub vcl_backend_response {
   set beresp.ttl = 600s;
}
sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT from Varnish cache" ;
    } else {
        set resp.http.X-Cache = "MISS";
    }
}

Create Secret

Create a secret for Varnish cli admin operations

kubectl create secret generic varnish-secret --from-literal=secret=$(head -c32 /dev/urandom  | base64)

Setup

Apply the following yaml file, replicas and environment variables can be adjusted to your need. This will deploy the Varnish service and Varnish proxy pods. The container is now based up on Alpine Linux and Varnish 6.4

---
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations: {}
  labels: {}
  name: varnish-proxy
  namespace: default
  resourceVersion: '293478564'
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: varnish-proxy
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      annotations:
        kubectl.kubernetes.io/restartedAt: '2022-10-25T15:33:54+08:00'
      creationTimestamp: null
      labels:
        app: varnish-proxy
      name: varnish-proxy
    spec:
      containers:
        - env:
            - name: CACHE_SIZE
              value: 128m
            - name: VCL_CONFIG
              value: /etc/varnish/configmap/varnish.vcl
            - name: SECRET_FILE
              value: /etc/varnish/k8s-secret/secret
            - name: VARNISHD_PARAMS
              value: '-p default_ttl=3600 -p default_grace=3600'
          image: 'dkruyt/varnish:alpine'
          imagePullPolicy: Always
          name: varnish
          ports:
            - containerPort: 80
              protocol: TCP
          resources: {}
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          volumeMounts:
            - mountPath: /etc/varnish/configmap
              name: varnish-config
            - mountPath: /etc/varnish/k8s-secret
              name: varnish-secret
            - mountPath: /var/lib/varnish
              name: shared-data
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
        - configMap:
            defaultMode: 420
            items:
              - key: varnish.vcl
                path: varnish.vcl
            name: varnish-vcl
          name: varnish-config
        - name: varnish-secret
          secret:
            defaultMode: 420
            secretName: varnish-secret
        - emptyDir: {}
          name: shared-data


Varnish help parameter

Basic options:
  -a [<name>=]address[:port][,proto] # HTTP listen address and port
     [,user=<u>][,group=<g>]   # Can be specified multiple times.
     [,mode=<m>]               #   default: ":80,HTTP"
                               # Proto can be "PROXY" or "HTTP" (default)
                               # user, group and mode set permissions for
                               #   a Unix domain socket.
  -b [addr[:port]|path]        # Backend address and port
                               #   or socket file path
                               #   default: ":80"
  -f vclfile                   # VCL program
                               # Can be specified multiple times.
  -n dir                       # Working directory

-b can be used only once, and not together with -f

Documentation options:
  -?                           # Prints this usage message
  -x parameter                 # Parameter documentation
  -x vsl                       # VSL record documentation
  -x cli                       # CLI command documentation
  -x builtin                   # Builtin VCL program
  -x optstring                 # List of getopt options

Operations options:
  -F                           # Run in foreground
  -T address[:port]            # CLI address
                               # Can be specified multiple times.
  -M address:port              # Reverse CLI destination
                               # Can be specified multiple times.
  -P file                      # PID file
  -i identity                  # Identity of varnish instance
  -I clifile                   # Initialization CLI commands

Tuning options:
  -t TTL                       # Default TTL
  -p param=value               # set parameter
                               # Can be specified multiple times.
  -s [name=]kind[,options]     # Storage specification
                               # Can be specified multiple times.
                               #   -s default (=malloc)
                               #   -s malloc
                               #   -s file
  -l vsl                       # Size of shared memory log
                               #   vsl: space for VSL records [80m]

Security options:
  -r param[,param...]          # Set parameters read-only from CLI
                               # Can be specified multiple times.
  -S secret-file               # Secret file for CLI authentication
  -j jail[,options]            # Jail specification
                               #   -j unix
                               #   -j none

Advanced/Dev/Debug options:
  -d                           # debug mode
                               # Stay in foreground, CLI on stdin.
  -C                           # Output VCL code compiled to C language
  -V                           # version
  -h kind[,options]            # Hash specification
  -W waiter                    # Waiter implementation
2

评论区