天天看點

在 Kubernetes中,fluentd 以 sidecar 模式收集日志,并發送至 ElasticSearch

在 Kubernetes中,fluentd 以 sidecar 模式收集日志,并發送至 ElasticSearch

sidecar

1. 簡介

ElasticSearch 在日志收集和分析領域非常流行,而 fluentd 是一種萬用型的日志收集器,當然也支援 ES(ElasticSearch)。不過在 Kubnernetes 環境中,問題會變得有點複雜,問題在于是否要把 fluentd 放進跑業務代碼的容器裡:放在一起的話,fluentd 明顯和業務無關;不放在一起的話,fluentd 又如何通路到跑業務容器裡的日志呢。

在 Kubernetes中,fluentd 以 sidecar 模式收集日志,并發送至 ElasticSearch

fluentd

這個問題有多種解決方式,感興趣的話,可以參考這個連結:

Logging Architecture

。在這裡要介紹的是 sidecar 模式,sidecar 就是題圖中的摩托挎鬥,對應到 Kubernetes 中,就是在 Pod 中再加一個 container 來跑非核心的代碼,來保證隔離性,并盡量縮減容器鏡像的大小。

2. 部署

接下來我們就開始部署吧,要先準備好 fluentd 的配置檔案,<source> 部分指定的是要上傳的日志檔案;<match> 部分指定的是日志要傳輸到哪裡,這裡指定的就是 ElasticSearch,真正使用的時候要注意根據具體環境替換 <ES-IP>。

$ cat fluentd-config-sidecar.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluentd-config
data:
  fluentd.conf: |
    <source>
      type tail
      format none
      path /var/log/1.log
      pos_file /var/log/1.log.pos
      tag count.format1
    </source>

    <source>
      type tail
      format none
      path /var/log/2.log
      pos_file /var/log/2.log.pos
      tag count.format2
    </source>

    <match **>
      type elasticsearch
      host <ES-IP>
      port 9200
      include_tag_key true
      tag_key @log_name
      logstash_format true
      flush_interval 10s
    </match>
           

接下來是建立 Pod 的 yaml 檔案,其中包含了兩個 container:count 和 count-agent。count 是主程式,産生日志;count-agent 是發送日志的 sidecar。這裡面由幾處需要注意一下:

  • emptyDir:表示建立一個空的目錄,之是以用這個種方式挂載日志,原因是 emptyDir 對 Pod 内的全部 container 都可見。
  • fluentd 使用的鏡像:原來的鏡像是存放在 google container registry 裡的,國内無法通路,是以使用了阿裡雲的源作為替代。
  • FLUENTD_ARGS 環境變量:是 fluentd 的啟動參數。
$ cat counter-pod-sidecar.yaml
apiVersion: v1
kind: Pod
metadata:
  name: counter
spec:
  containers:
  - name: count
    image: busybox
    args:
    - /bin/sh
    - -c
    - >
      i=0;
      while true;
      do
        echo "$i: $(date)" >> /var/log/1.log;
        echo "$(date) INFO $i" >> /var/log/2.log;
        i=$((i+1));
        sleep 1;
      done
    volumeMounts:
    - name: varlog
      mountPath: /var/log
  - name: count-agent
    image: registry.cn-beijing.aliyuncs.com/k8s-mqm/fluentd-elasticsearch:v2.1.0
    env:
    - name: FLUENTD_ARGS
      value: -c /etc/fluentd-config/fluentd.conf
    volumeMounts:
    - name: varlog
      mountPath: /var/log
    - name: config-volume
      mountPath: /etc/fluentd-config
  volumes:
  - name: varlog
    emptyDir: {}
  - name: config-volume
    configMap:
      name: fluentd-config
           

3. 參考文檔