You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fluentd是否支持文件输出日志轮转?Docker Compose场景问询

实现Docker Compose容器日志按容器名拆分存储(基于Fluentd)

我来帮你完善这个按容器拆分日志的Fluentd配置方案,结合Docker Compose的场景给你完整的实现步骤:

1. 完整的Fluentd配置文件(fluent.conf)

你已经配置了in_forward源,接下来补充按容器拆分日志的核心匹配规则,同时加上日志解析的过滤规则(适配Docker默认的JSON格式日志):

<source>
  @type forward
  port 24224
  bind 0.0.0.0
</source>

# 解析Docker默认的JSON格式日志(可选,若容器输出纯文本可删除)
<filter docker.**>
  @type parser
  key_name log
  <parse>
    @type json
    time_key time
    time_format %Y-%m-%dT%H:%M:%S.%L%Z
  </parse>
</filter>

# 核心:按容器/服务名拆分日志文件
<match docker.**>
  @type file
  # 用tag的第二部分作为容器名(比如tag是docker.nginx,就提取nginx)
  path /var/log/fluentd/containers/${tag_parts[1]}/app.log
  # 日志滚动与压缩配置
  rotate_wait 5
  compress gzip
  time_slice_format %Y%m%d  # 按天滚动日志
  time_slice_wait 10m
  time_format %Y-%m-%dT%H:%M:%S%z

  # 可选:添加缓冲区防止日志丢失
  <buffer>
    @type file
    path /var/log/fluentd/buffers/${tag_parts[1]}
    flush_interval 10s
    retry_max_times 3
  </buffer>
</match>

2. Docker Compose配置示例

要让栈内所有容器把日志转发到Fluentd,需要给每个服务配置fluentd日志驱动,同时定义Fluentd服务:

version: '3.8'

services:
  fluentd:
    image: fluent/fluentd:v1.16-debian-1
    volumes:
      - ./fluent.conf:/fluentd/etc/fluent.conf  # 挂载自定义配置
      - ./container-logs:/var/log/fluentd/containers  # 持久化日志
      - ./fluentd-buffers:/var/log/fluentd/buffers  # 持久化缓冲区
    ports:
      - "24224:24224"
      - "24224:24224/udp"
    networks:
      - logging-network

  # 示例服务:Nginx
  nginx:
    image: nginx:alpine
    logging:
      driver: fluentd
      options:
        fluentd-address: fluentd:24224  # 同栈内用服务名直接访问
        tag: docker.nginx  # 标记日志归属,对应Fluentd配置里的tag
    networks:
      - logging-network

  # 示例服务:MySQL
  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root123
    logging:
      driver: fluentd
      options:
        fluentd-address: fluentd:24224
        tag: docker.mysql
    networks:
      - logging-network

networks:
  logging-network:
    driver: bridge

3. 关键注意事项

  • 插件依赖:如果你的Fluentd镜像缺少解析插件,可以自定义Dockerfile构建:
    FROM fluent/fluentd:v1.16-debian-1
    USER root
    RUN gem install fluent-plugin-parser
    USER fluent
    
  • 权限问题:确保Fluentd容器对挂载的日志目录有读写权限,启动前可以手动创建目录并设置权限:mkdir -p container-logs fluentd-buffers && chown -R 1000:1000 container-logs fluentd-buffers
  • 日志可靠性:添加缓冲区配置后,即使Fluentd临时重启,未写入的日志会存在缓冲区里,恢复后自动补写

内容的提问来源于stack exchange,提问作者Rh1303

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:18:18