# OpenTelemetry Docker Logs: Collect and Enrich Container Logs

> Collect OpenTelemetry Docker logs with file_log, docker_observer, and receiver_creator, then attach container name, image, ID, and labels.

Source: https://last9.io/blog/opentelemetry-docker-logs/

Docker logs look easy until you want useful resource attributes. The Docker JSON log file gives you a timestamp, stream, and message. The file path gives you the container ID. It does not give you the container name, image name, Compose service, deployment environment, or the labels your team uses to route incidents.

Kubernetes log collection gets a cleaner path. The OpenTelemetry `container` operator can read Kubernetes pod log paths and derive `k8s.namespace.name`, `k8s.pod.name`, and `k8s.container.name`. A Docker host does not have that pod path structure. If you tail `/var/lib/docker/containers/*/*-json.log` with one static `file_log` receiver, the Collector can parse the Docker log wrapper, but it cannot infer the rest of the container metadata from the file name alone.

The native Collector pattern is to combine [`docker_observer`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/observer/dockerobserver) with [`receiver_creator`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/receivercreator). `docker_observer` discovers running containers through the Docker API. `receiver_creator` starts a `file_log` receiver for each matching container and attaches resource attributes from the discovered endpoint.

This post shows that pattern, the socket access it requires, and the fallback when you cannot mount the Docker socket.

## Why Kubernetes gets metadata from the path and Docker does not

The OpenTelemetry `container` operator parses `docker`, `cri-o`, and `containerd` log formats. It also has a Kubernetes-specific convenience: when `log.file.path` is present, it can add Kubernetes metadata from paths such as `/var/log/pods/<namespace>_<pod>_<uid>/<container>/<restart>.log`.

That works because Kubernetes encodes namespace, pod, UID, container name, and restart count in the file path. Docker's default JSON log path has a different shape:

```text
/var/lib/docker/containers/<container_id>/<container_id>-json.log
```

That path is enough to identify the container. It is not enough to know the container's human-readable name, image, labels, or Compose service. Those fields live in Docker daemon metadata, available through container inspect data and the Docker API.

This distinction is why a static `file_log` receiver feels incomplete on Docker hosts. It can read and parse the log line, but it does not have the metadata lookup step that Kubernetes gets from the pod path.

## Use docker_observer and receiver_creator for Docker logs

The Collector Contrib distribution includes the two pieces you need:

- `docker_observer`: a beta extension that watches Docker events and reports running container endpoints.
- `receiver_creator`: a receiver that can instantiate receivers at runtime when an observed endpoint matches a rule. Its logs support is alpha, while metrics support is beta.

For Docker logs, set `include_all_containers: true` on `docker_observer`. The upstream docs say this emits a port-less endpoint for every running container, which lets you create one log receiver per container with a rule such as `type == "container" and port == 0`.

A working shape looks like this:

```yaml
extensions:
  docker_observer:
    endpoint: unix:///var/run/docker.sock
    include_all_containers: true

  file_storage:
    directory: /var/lib/otelcol/file_storage

receivers:
  receiver_creator/docker_logs:
    watch_observers: [docker_observer]
    receivers:
      file_log/docker:
        rule: type == "container" and port == 0
        config:
          include:
            - /var/lib/docker/containers/`container_id`/*-json.log
          start_at: end
          include_file_path: true
          include_file_name: true
          storage: file_storage
          operators:
            - type: container
              id: parse-docker-json
              format: docker
              add_metadata_from_filepath: false
        resource_attributes:
          container.id: '`container_id`'
          docker.label.com_docker_compose_service: '`labels["com.docker.compose.service"]`'
          docker.label.com_docker_compose_project: '`labels["com.docker.compose.project"]`'

processors:
  memory_limiter:
    check_interval: 1s
    limit_mib: 512
    spike_limit_mib: 128

  transform/docker_service:
    error_mode: ignore
    log_statements:
      - context: resource
        statements:
          - set(attributes["service.name"], attributes["docker.label.com_docker_compose_service"]) where attributes["service.name"] == nil and attributes["docker.label.com_docker_compose_service"] != nil
          - set(attributes["service.name"], attributes["container.name"]) where attributes["service.name"] == nil and attributes["container.name"] != nil

  batch:
    send_batch_size: 8192
    timeout: 5s

exporters:
  otlp:
    endpoint: ${env:OTLP_ENDPOINT}
    headers:
      Authorization: ${env:OTLP_AUTH_HEADER}

service:
  extensions: [docker_observer, file_storage]
  pipelines:
    logs:
      receivers: [receiver_creator/docker_logs]
      processors: [memory_limiter, transform/docker_service, batch]
      exporters: [otlp]
```

A few details matter:

- `docker_observer` needs Docker API access to emit endpoints with `name`, `image`, `container_id`, and `labels`.
- `receiver_creator` sets `container.name` and `container.image.name` by default for `type == "container"` endpoints, according to its README.
- `container.id` is not listed as a default for `type == "container"`, so the config maps it explicitly.
- Docker labels can be high-cardinality. Map only labels you already use for operational grouping, such as Compose service or environment. Avoid request, tenant, user, and build labels unless your backend is designed for that cardinality.
- `file_storage` persists file offsets. Without it, the `file_log` receiver keeps offsets in memory and resumes according to `start_at` after a Collector restart.

Use `file_log` in new configs. `filelog` still works as a deprecated alias in current Collector Contrib versions, but mixing both names inside one config makes troubleshooting harder.

## Run the Collector with the right mounts

The Collector container needs two host mounts for this pattern:

1. Docker socket access for `docker_observer`.
2. Docker log file access for `file_log`.

A minimal Compose service looks like this:

```yaml
services:
  otel-collector:
    image: otel/opentelemetry-collector-contrib:latest
    command: ["--config=/etc/otelcol/config.yaml"]
    user: "0"
    volumes:
      - ./otelcol-config.yaml:/etc/otelcol/config.yaml:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /var/lib/docker/containers:/var/lib/docker/containers:ro
      - otel-file-storage:/var/lib/otelcol/file_storage
    environment:
      OTLP_ENDPOINT: ${OTLP_ENDPOINT}
      OTLP_AUTH_HEADER: ${OTLP_AUTH_HEADER}
    restart: unless-stopped

volumes:
  otel-file-storage:
```

Read-only mounts are the safer default for logs and the Docker socket, but do not treat `/var/run/docker.sock:ro` as harmless. The Docker API can still expose container names, images, labels, environment-derived metadata, network settings, and events. In many deployments, access to the Docker socket is treated as high privilege because Docker daemon access can reveal or control host-level container state depending on the API calls and daemon configuration.

If your security boundary does not allow the Collector to read the Docker socket, skip to the fallback section. Do not work around the policy by mounting the socket into an untrusted sidecar.

## Parse Docker JSON without Kubernetes path metadata

The Docker `json-file` logging driver stores records with fields like `log`, `stream`, and `time`. Docker's docs also warn that these files are designed for Docker itself and that external tools should avoid interfering with them. For collection, mount the files read-only and let the Collector tail them.

The `container` operator in the config above parses that wrapper with `format: docker`. Set `add_metadata_from_filepath: false` on Docker hosts. The Kubernetes metadata parser expects a Kubernetes pod log path. A Docker path under `/var/lib/docker/containers` will not provide namespace, pod, or container-name fields.

After the `container` operator runs, the application message is the log body, and Docker stream data is available as attributes. Add JSON parsing only if your application log body is JSON:

```yaml
operators:
  - type: container
    id: parse-docker-json
    format: docker
    add_metadata_from_filepath: false
  - type: json_parser
    id: parse-app-json
    if: body matches "^\\{"
    parse_from: body
    parse_to: attributes
```

Keep parser failures visible in Collector logs while you test. Avoid sending every line into a JSON parser if some services write plain text.

## Derive service names from labels, not container IDs

A container ID is stable enough for correlation, but it is a poor service name. It changes when the container is recreated, is not meaningful to humans, and fragments dashboards if you group by it.

Prefer service metadata in this order:

1. `service.name` emitted by the application through OpenTelemetry SDK resource attributes.
2. A Docker or Compose label that names the workload, such as `com.docker.compose.service`.
3. The Docker container name as a fallback.
4. `container.id` only for drill-down and exact container correlation.

The `transform/docker_service` processor in the full config above follows that order. It keeps `service.name` if the application already set it, then fills it from the Compose service label, then from the container name.

If you send logs to Last9, our [Docker integration docs](/docs/integrations/containers-and-k8s/docker/) cover the broader Docker monitoring setup, and the [OpenTelemetry Collector docs](/docs/integrations/observability/opentelemetry-collector/) show the OTLP wiring. For filtering, redaction, and transforms before export, use the [processors and transforms guide](/docs/integrations/observability/opentelemetry-collector/processors-and-transforms/).

## Fallback when you cannot mount the Docker socket

If the Collector cannot read the Docker API, a static `file_log` receiver can still collect Docker JSON logs. You lose daemon metadata unless you add it before the log reaches the file or through a separate lookup outside this pipeline.

```yaml
extensions:
  file_storage:
    directory: /var/lib/otelcol/file_storage

receivers:
  file_log/docker_static:
    include:
      - /var/lib/docker/containers/*/*-json.log
    start_at: end
    include_file_path: true
    include_file_name: true
    storage: file_storage
    operators:
      - type: container
        id: parse-docker-json
        format: docker
        add_metadata_from_filepath: false
      - type: regex_parser
        id: container-id-from-path
        parse_from: attributes["log.file.path"]
        regex: '^/var/lib/docker/containers/(?P<container_id>[a-f0-9]{64})/[a-f0-9]{64}-json\.log$'
        parse_to: resource
      - type: move
        from: resource["container_id"]
        to: resource["container.id"]

service:
  extensions: [file_storage]
  pipelines:
    logs:
      receivers: [file_log/docker_static]
      processors: [memory_limiter, batch]
      exporters: [otlp]
```

`memory_limiter`, `batch`, and `otlp` are the same as in the main config. The `move` step renames the captured ID to `container.id`, so both setups produce the same attribute.

This fallback gives you `container.id` from the path. It does not give you the container name, image, or labels. Do not infer service names from short IDs. If you need those fields without socket access, push them into the application resource attributes, use Docker logging driver tag options, or enrich downstream from a controlled inventory source.

## Troubleshoot missing Docker metadata

Start with the two discovery points: can the Collector see containers, and can each created receiver read the right file?

| Symptom | Check | Likely fix |
| --- | --- | --- |
| No log records | `/var/lib/docker/containers` mount and file permissions | Mount the directory read-only and run the Collector with enough read permissions. |
| Logs arrive without name or image | `docker_observer` not running or not in `service.extensions` | Add `docker_observer` to `extensions` and `service.extensions`. |
| One receiver per exposed port | `include_all_containers` and discovery rule | Use `include_all_containers: true` and `rule: type == "container" and port == 0`. |
| Container ID present, labels missing | Label mapping expression or label key | Verify the label exists with `docker inspect`, then test the backtick expression. |
| Duplicates after restart | Missing `file_storage` | Add a storage extension and reference it in the `file_log` config. |
| Kubernetes fields are empty | Docker path used with Kubernetes path parser | Set `add_metadata_from_filepath: false` for Docker JSON paths. |

Collector component stability also matters. `docker_observer` is beta. `receiver_creator` is alpha for logs. That does not mean you cannot use them, but it does mean you should pin a Collector version, run the config in staging, and read release notes before upgrades.

There is no `dockerattributes` processor in the current contrib processor directory checked for this draft. If you see examples that mention one, verify the component exists in the Collector distribution you run before designing around it.

## When a logging driver or Fluent Bit is the better fit

The Collector pattern is a good fit when you already run OpenTelemetry Collector on Docker hosts and want logs to share the same processors, exporters, and resource schema as the rest of your telemetry.

Use a Docker logging driver when you want Docker to send logs directly to another transport and you accept the behavior change at container runtime. Drivers can attach tags, labels, or environment fields depending on the driver and daemon options, but they also change how logs are stored and accessed. Some remote drivers affect `docker logs` behavior unless dual logging is enabled.

Use Fluent Bit when you need a mature file tailer with Docker metadata lookup, buffering, and routing features your current Collector version does not cover. Fluent Bit is still common in container log pipelines, especially when teams already operate it. The tradeoff is one more agent and one more configuration language.

Use static `file_log` without the socket when security policy blocks Docker API access and container ID is enough. That setup is simpler, but the missing name, image, and labels are a real limit. Make that tradeoff explicit before you ship dashboards or alerts that depend on service-level grouping.

## FAQ

### How do I collect Docker logs with OpenTelemetry?

Use the OpenTelemetry Collector Contrib distribution with `docker_observer`, `receiver_creator`, and a `file_log` receiver template. Mount `/var/run/docker.sock` so `docker_observer` can discover running containers, and mount `/var/lib/docker/containers` so `file_log` can read each container's JSON log file.

### Can the OpenTelemetry Collector add Docker container metadata to logs?

Yes, `receiver_creator` can add `container.name` and `container.image.name` by default for Docker container endpoints discovered by `docker_observer`. You can also map `container.id` and selected Docker labels as resource attributes.

### What permissions does docker_observer need?

`docker_observer` needs read access to the Docker Engine API, usually through `/var/run/docker.sock` on Linux. Treat that socket as sensitive because it exposes container inspect data, image names, labels, events, and other daemon metadata.

### Should I use file_log or filelog in Collector configs?

Use `file_log` in new configs. `filelog` still works as a deprecated alias in current Collector Contrib versions, but new examples should use `file_log` and keep receiver names consistent in the pipeline.
