1. 簡介
ElasticSearch 在日志收集和分析領(lǐng)域非常流行靡羡,而 fluentd 是一種萬用型的日志收集器系洛,當(dāng)然也支持 ES(ElasticSearch)俊性。不過在 Kubnernetes 環(huán)境中,問題會(huì)變得有點(diǎn)復(fù)雜描扯,問題在于是否要把 fluentd 放進(jìn)跑業(yè)務(wù)代碼的容器里:放在一起的話定页,fluentd 明顯和業(yè)務(wù)無關(guān);不放在一起的話绽诚,fluentd 又如何訪問到跑業(yè)務(wù)容器里的日志呢典徊。
這個(gè)問題有多種解決方式,感興趣的話恩够,可以參考這個(gè)鏈接:Logging Architecture卒落。在這里要介紹的是 sidecar 模式,sidecar 就是題圖中的摩托挎斗蜂桶,對(duì)應(yīng)到 Kubernetes 中儡毕,就是在 Pod 中再加一個(gè) container 來跑非核心的代碼,來保證隔離性扑媚,并盡量縮減容器鏡像的大小腰湾。
2. 部署
接下來我們就開始部署吧,要先準(zhǔn)備好 fluentd 的配置文件疆股,<source> 部分指定的是要上傳的日志文件费坊;<match> 部分指定的是日志要傳輸?shù)侥睦铮@里指定的就是 ElasticSearch旬痹,真正使用的時(shí)候要注意根據(jù)具體環(huán)境替換 <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>
接下來是創(chuàng)建 Pod 的 yaml 文件,其中包含了兩個(gè) container:count 和 count-agent两残。count 是主程序永毅,產(chǎn)生日志;count-agent 是發(fā)送日志的 sidecar人弓。這里面由幾處需要注意一下:
- emptyDir:表示創(chuàng)建一個(gè)空的目錄卷雕,之所以用這個(gè)種方式掛載日志,原因是 emptyDir 對(duì) Pod 內(nèi)的全部 container 都可見票从。
- fluentd 使用的鏡像:原來的鏡像是存放在 google container registry 里的,國內(nèi)無法訪問滨嘱,所以使用了阿里云的源作為替代峰鄙。
- FLUENTD_ARGS 環(huán)境變量:是 fluentd 的啟動(dòng)參數(shù)。
$ 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