9

K8s~为pod添加sidecar进行日志收集

 4 years ago
source link: http://www.cnblogs.com/lori/p/12179502.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

我们在k8s部署服务时,一般来说一个服务会对应一类pod,而pod通过rs实现副本集,而这些pod的日志一般有控制台stdout和文件的,一般会把这些日志最终输出到elasticsearch里,再通过kabana进行分析,而在实现由pod到elasticsearch(es)时有多种方法,下面我列举一下:

  1. 直接从标准控制台 stdout中通过fluentd进行收集,再存到es( 早期docker有实现)
  2. 通过logback里的fluentd包,直接把日志输出到fluentd,再存到es
  3. 在k8s里,可以为pod添加一个边车(边斗,sidecar),这个边车主要是fluentd插件,从容器日志文件里读取日志,收集到es

从上面的解析可以看到第1种如果你是docker swarm环境可以使用,而第2种与业务代码耦合太紧也不合适,只有第三种是未来的趋势,目前大都是使用这种方式!

实现方式

1 sidecar的fluentd的mapconfig

apiVersion: v1
kind: ConfigMap
metadata:
  name: fluentd-config
  namespace: saas
data:
  fluentd.conf: |
    <source>
      type tail
      format none
      path /var/log/*.log
      pos_file /var/log/log.pos
      tag saas
    </source>

    <match **>
      @id elasticsearch
      @type elasticsearch
      @log_level debug
      index_name fluentd
      type_name _doc
      host elasticsearch.elk
      port 9200
      include_tag_key true
      tag_key @log_name
      logstash_format true
      flush_interval 10s
    </match>

运行

kubectl create -f fluentd-config-sidecar.yaml

测试一个pod,像容器输出日志到目录,定时反复输出

apiVersion: v1
kind: Pod
metadata:
  labels:
    example: logging-sidecar
  name: logging-sidecar-example
spec:
  containers:
  - name: synthetic-logger
    image: 172.17.0.22:8888/saas/hello-world:latest
    command: ["bash", "-c", "i=\"0\"; while true; do echo \"`hostname`: $i \" >> /var/log/1.log; date --rfc-3339 ns >> /var/log/1.log; sleep 4; i=$[$i+1]; done"]
    volumeMounts:
    - name: varlog
      mountPath: /var/log
  - name: sidecar-log-collector
    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

部署它

kubectl create -f fluentd-demo.yaml

然后去你的kabana里查看日志,可以按着@log_name字段去查询,这就是我们日志里的tag,这个我们可以在代码里配置,可以设置成一个namespace,这样方便日志的跟踪!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK