Docker 47 🐳 Centralized Log Aggregation: Shipping Docker Container Logs to ELK / Grafana Loki
A single container’s logs are accessible with docker logs. A hundred containers across ten hosts are not. The logs are scattered across the machines, and the search requires the SSH into each one. The centralized log aggregation solves the problem: the container logs are shipped to a central system, indexed, and searchable from the single interface. The two dominant stacks are the ELK (the Elasticsearch, the Logstash, the the Kibana) and the Grafana Loki (the Loki, the Promtail, the Grafana). The ELK is the powerful and the heavy, and the Loki is the lightweight and the cloud-native. The choice depends on the scale and the operational preference.
The ELK pipeline is the four components. The Filebeat runs on the Docker host, reads the container logs from the /var/lib/docker/containers/, and ships them to the Logstash . The Logstash parses the logs, extracts the fields, and sends them to the Elasticsearch, which indexes and stores them. The Kibana provides the search and the visualization . The Filebeat is the lightweight and the Logstash is the heavy, and the Kafka can be inserted between them for the buffering .
The Loki pipeline is the three components. The Promtail runs on the Docker host, discovers the containers via the Docker socket, reads the logs, and pushes them to the Loki . The Loki stores the logs with the labels and the compressed chunks, and the Grafana queries the Loki with the LogQL . The Loki indexes only the labels, not the full text, which makes it much cheaper to operate than the Elasticsearch .
This chapter covers three areas. First, why the centralized log aggregation exists — the multi-container problem and the centralized search. Second, the ELK pipeline — the Filebeat, the Logstash, the Elasticsearch, the Kibana, and the Docker configuration. Third, the Loki pipeline — the Promtail, the Loki, the Grafana, and the LogQL. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the two pipelines.
Key point: The centralized log aggregation ships the container logs to a central system for the search and the analysis. The ELK uses the Filebeat to read the Docker logs, the Logstash to parse, the Elasticsearch to store, and the Kibana to visualize. The Loki uses the Promtail to read the Docker logs, the Loki to store, and the Grafana to query with the LogQL. The ELK is the powerful and the heavy, and the Loki is the lightweight and the cloud-native.
Why the centralized log aggregation exists
The multi-container problem. A modern application runs the many containers: the API, the worker, the database, the cache, the reverse proxy. Each writes to its own log, and the docker logs shows only the one container at a time. The correlation requires the manual and the tedious. The centralized aggregation collects every container’s log in the one system, and the search spans the whole application .
The ephemeral problem. A container is the ephemeral. When the container is removed, its logs are removed with it. The logs that are needed for the debugging are gone. The centralized aggregation ships the logs off the host before the container is removed, and the retention is the property of the central system .
The search problem. The grep on the local log files is the line-by-line and the slow. The Elasticsearch and the Loki provide the indexed search, the filtering, the aggregation, and the visualization. The search for the specific request ID across the hundred containers is the seconds in the central system, and the hours in the local .
The label problem. The container log entry is the raw text, and the metadata — the container name, the image, the host, the labels — is lost. The Filebeat and the Promtail enrich the log entries with the Docker metadata, and the search can filter by the container name, the image, or the custom label .
The ELK-versus-Loki problem. The ELK is the mature and the feature-rich, and the heavy. The Elasticsearch requires the JVM and the significant RAM, and the Logstash is the resource-hungry . The Loki is the lightweight and the cloud-native, and the labels-only index makes the storage cheap. The trade-off is between the power of the full-text search and the cost of the lightweight .
The trade-off. The centralized logging adds the infrastructure: the servers, the storage, the maintenance. The Filebeat and the Promtail are the lightweight, and the Elasticsearch and the Loki are the heavy. The trade-off is between the operational cost of the central system and the debugging capability it provides.
a. The ELK pipeline
The ELK pipeline is the Filebeat, the Logstash, the Elasticsearch, and the Kibana.
The Filebeat. The Filebeat reads the Docker container logs from the /var/lib/docker/containers/*/*.log and ships them to the Logstash . The autodiscover provider detects the new containers and adds the metadata .
filebeat.autodiscover:
providers:
- type: docker
hints.enabled: true
processors:
- add_docker_metadata: ~
output.logstash:
hosts: ["logstash:5044"]
The hints.enabled allows the container labels to declare the log type. The add_docker_metadata adds the container name, the image, and the labels .
The Logstash. The Logstash receives the logs on the port 5044, parses them with the grok, extracts the timestamp and the log level, and sends them to the Elasticsearch .
input {
beats {
port => 5044
}
}
filter {
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:message}" }
}
date {
match => ["timestamp", "ISO8601"]
target => "@timestamp"
}
}
output {
elasticsearch {
hosts => ["http://es:9200"]
index => "docker-logs-%{+YYYY.MM.dd}"
}
}
The grok pattern parses the log line, and the date filter sets the @timestamp .
The Elasticsearch. The Elasticsearch stores the parsed logs in the daily indices. The xpack.security.enabled=false disables the security for the development, and the production should enable it .
The Kibana. The Kibana provides the search and the visualization. The index pattern docker-logs-* matches the daily indices, and the Discover tab shows the logs .
The Docker configuration. The container must use the json-file driver, and the Filebeat reads the JSON files .
services:
app:
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
labels: "service,app"
The labels option adds the metadata to the log entries, and the max-size and the max-file prevent the disk exhaustion .
b. The Loki pipeline
The Loki pipeline is the Promtail, the Loki, and the Grafana.
The Promtail. The Promtail discovers the Docker containers via the Docker socket, reads the logs, and pushes them to the Loki .
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
refresh_interval: 5s
relabel_configs:
- source_labels: ['__meta_docker_container_name']
regex: '/(.*)'
target_label: 'container'
The docker_sd_configs discovers the containers, and the relabel_configs extracts the container name as the label .
The Loki. The Loki stores the logs in the compressed chunks, and the index contains only the labels .
auth_enabled: false
server:
http_listen_port: 3100
common:
path_prefix: /tmp/loki
storage:
filesystem:
chunks_directory: /tmp/loki/chunks
rules_directory: /tmp/loki/rules
replication_factor: 1
schema_config:
configs:
- from: 2020-10-24
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
The filesystem storage is the local, and the tsdb is the index store. The schema_config defines the index period .
The Grafana. The Grafana connects to the Loki as the data source, and the LogQL queries the logs.
{container="app"} |= "error"
{container="app"} | json | level="ERROR"
count_over_time({container="app"} |= "error" [5m])
The {container="app"} selects the label, the |= "error" filters the text, and the | json parses the JSON .
The Docker Compose. The three services run in the single Compose file.
services:
loki:
image: grafana/loki:3.0.0
ports: ["3100:3100"]
command: ["-config.file=/etc/loki/local-config.yaml"]
promtail:
image: grafana/promtail:3.0.0
volumes:
- /var/log:/var/log:ro
- /var/run/docker.sock:/var/run/docker.sock
- ./promtail.yaml:/etc/promtail/config.yml
command: ["-config.file=/etc/promtail/config.yml"]
grafana:
image: grafana/grafana:11.1.0
ports: ["3000:3000"]
environment: { GF_SECURITY_ADMIN_PASSWORD: admin }
The Promtail mounts the Docker socket and the Promtail configuration, and the Grafana exposes the port 3000 .
c. The patterns and the comparison
The ELK for the full-text search. The ELK is the choice when the full-text search is the requirement. The Elasticsearch indexes every field, and the Kibana provides the complex queries and the aggregations. The cost is the resources: the Elasticsearch needs the 2-4 GB of the JVM heap, and the Logstash needs the 256 MB to 1 GB .
The Loki for the cost-sensitive. The Loki is the choice when the cost matters. The labels-only index makes the storage cheap, and the query is the grep-like and the fast. The trade-off is the lack of the full-text index: the |= "error" scans the chunks and filters the lines .
The Kafka for the buffering. The high-throughput pipeline inserts the Kafka between the Filebeat and the Logstash. The Kafka buffers the logs, handles the spikes, and provides the replay .
The sidecar for the file logs. The application that writes to the file instead of the stdout needs the sidecar. The Fluent Bit or the Filebeat runs beside the container, reads the shared volume, and ships the logs .
The label for the routing. The container labels route the logs to the different pipelines. The filebeat_ingest: 'true' enables the ingestion, and the logging=promtail enables the Promtail .
Complete Example Session
# ============================================
# PART 1: THE ELK COMPOSE
# ============================================
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.5.0
environment:
- discovery.type=single-node
- xpack.security.enabled=false
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ports:
- "9200:9200"
logstash:
image: docker.elastic.co/logstash/logstash:8.5.0
volumes:
- ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf
ports:
- "5044:5044"
depends_on:
- elasticsearch
kibana:
image: docker.elastic.co/kibana/kibana:8.5.0
ports:
- "5601:5601"
environment:
- ELASTICSEARCH_URL=http://elasticsearch:9200
filebeat:
image: docker.elastic.co/beats/filebeat:8.5.0
volumes:
- ./filebeat.yml:/usr/share/filebeat/filebeat.yml
- /var/lib/docker/containers:/var/lib/docker/containers:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
command: filebeat -e -strict.perms=false
depends_on:
- logstash
# ============================================
# PART 2: THE FILEBEAT CONFIG
# ============================================
filebeat.autodiscover:
providers:
- type: docker
hints.enabled: true
processors:
- add_docker_metadata: ~
output.logstash:
hosts: ["logstash:5044"]
# ============================================
# PART 3: THE LOGSTASH CONFIG
# ============================================
input {
beats { port => 5044 }
}
filter {
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:message}" }
}
date {
match => ["timestamp", "ISO8601"]
target => "@timestamp"
}
}
output {
elasticsearch {
hosts => ["http://elasticsearch:9200"]
index => "docker-logs-%{+YYYY.MM.dd}"
}
}
# ============================================
# PART 4: THE LOKI COMPOSE
# ============================================
services:
loki:
image: grafana/loki:3.0.0
ports: ["3100:3100"]
command: ["-config.file=/etc/loki/local-config.yaml"]
promtail:
image: grafana/promtail:3.0.0
volumes:
- /var/log:/var/log:ro
- /var/run/docker.sock:/var/run/docker.sock
- ./promtail.yaml:/etc/promtail/config.yml
command: ["-config.file=/etc/promtail/config.yml"]
grafana:
image: grafana/grafana:11.1.0
ports: ["3000:3000"]
environment: { GF_SECURITY_ADMIN_PASSWORD: admin }
# ============================================
# PART 5: THE PROMTAIL CONFIG
# ============================================
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
refresh_interval: 5s
relabel_configs:
- source_labels: ['__meta_docker_container_name']
regex: '/(.*)'
target_label: 'container'
# ============================================
# PART 6: THE DOCKER LOG CONFIGURATION
# ============================================
services:
app:
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
labels: "service,app"
# ============================================
# PART 7: THE GRAFANA DATASOURCE
# ============================================
# In the Grafana UI:
# Configuration → Data Sources → Add Loki
# URL: http://loki:3100
# Save & Test
# ============================================
# PART 8: THE LOGQL QUERIES
# ============================================
# All the logs from the app container
{container="app"}
# The error logs
{container="app"} |= "error"
# The JSON level filter
{container="app"} | json | level="ERROR"
# The error count per 5 minutes
count_over_time({container="app"} |= "error" [5m])
# ============================================
# PART 9: THE KIBANA SEARCH
# ============================================
# The index pattern: docker-logs-*
# The Discover tab: the log entries
# The filter: level:ERROR
# The search: message:"the request id"
# ============================================
# PART 10: THE LFCS PIPELINE
# ============================================
# The ELK pipeline
docker compose -f docker-compose-elk.yml up -d
# The Kibana: http://localhost:5601
# The Loki pipeline
docker compose -f docker-compose-loki.yml up -d
# The Grafana: http://localhost:3000
# The comparison
# The ELK: the full-text search, the heavy
# The Loki: the label search, the lightweight
The ten parts show the ELK Compose, the Filebeat config, the Logstash config, the Loki Compose, the Promtail config, the Docker log configuration, the Grafana data source, the LogQL queries, the Kibana search, and the LFCS pipeline.
Quick Reference
The ELK Components
| Component | The role |
|---|---|
| Filebeat | The log shipper |
| Logstash | The parser |
| Elasticsearch | The store |
| Kibana | The visualization |
The Loki Components
| Component | The role |
|---|---|
| Promtail | The log shipper |
| Loki | The store |
| Grafana | The visualization |
The Docker Configuration
| The option | The purpose |
|---|---|
driver: json-file | The required for the Filebeat |
max-size | The rotation |
max-file | The file count |
labels | The metadata |
The LogQL Queries
| The query | The purpose |
|---|---|
{container="app"} | The label select |
|= "error" | The text filter |
| json | The JSON parse |
count_over_time(...) | The aggregation |
The Ports
| The service | The port |
|---|---|
| Elasticsearch | 9200 |
| Logstash | 5044 |
| Kibana | 5601 |
| Loki | 3100 |
| Grafana | 3000 |
| Promtail | 9080 |
Best Practices
✅ Do This:
# Use the json-file driver with the rotation
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3" # ✅
# Use the autodiscover for the Filebeat
filebeat.autodiscover:
providers:
- type: docker
hints.enabled: true # ✅
# Use the docker_sd_configs for the Promtail
scrape_configs:
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock # ✅
# Use the labels for the routing
labels: "service,app,env" # ✅
# Use the non-blocking mode for the high volume
--log-opt mode=non-blocking --log-opt max-buffer-size=4m # ✅
❌ Don’t Do This:
# Don't use the json-file without the rotation
logging:
driver: json-file
# The disk fills up # ❌
# Don't forget the Docker socket mount
volumes:
- /var/lib/docker/containers:/var/lib/docker/containers:ro
# The missing /var/run/docker.sock # ❌
# Don't use the syslog for the ELK
logging:
driver: syslog
# The Logstash does not parse the syslog format # ❌
# Don't skip the metadata
processors:
# The add_docker_metadata is missing # ❌
# Don't use the Loki for the full-text search
# The labels-only index # ❌
# Don't forget the Grafana data source
# The Loki is not connected # ❌
Common Pitfalls
| The pitfall | The why | The fix |
|---|---|---|
| The logs are not shipped | The wrong driver | Use the json-file |
| The metadata is missing | The no processors | Use the add_docker_metadata |
| The disk fills up | The no rotation | Use the max-size and the max-file |
| The Promtail does not scrape | The missing socket | Mount the /var/run/docker.sock |
| The Loki retention | The default 168h | Configure the retention |
| The ELK is slow | The heavy Logstash | Use the Kafka or the Filebeat direct to ES |
| The Kibana index pattern | The wrong pattern | Use the docker-logs-* |
Real-World Examples
1. The Filebeat Autodiscover
filebeat.autodiscover:
providers:
- type: docker
hints.enabled: true
2. The Logstash Grok
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:message}" }
}
3. The Promtail Docker SD
docker_sd_configs:
- host: unix:///var/run/docker.sock
4. The Docker Labels
labels: "service,app"
5. The LogQL
{container="app"} |= "error"
6. The Kibana Search
level:ERROR AND message:"request id"
7. The Kafka Buffer
output.kafka:
hosts: ["kafka:9092"]
topic: "logs"
8. The Sidecar
volumes:
- ./logs:/app/logs
9. The Grafana Data Source
URL: http://loki:3100
10. The Complete
services:
app:
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
labels: "service,app"
Visual
The ELK Pipeline
┌──────────────────────────────────────────────────────────────┐
│ THE ELK PIPELINE │
│ │
│ The container: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ stdout / stderr │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the json-file driver │
│ ▼ │
│ The Docker host: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ /var/lib/docker/containers/*/*.log │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the Filebeat reads │
│ ▼ │
│ The Filebeat: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the autodiscover + the metadata │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the port 5044 │
│ ▼ │
│ The Logstash: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the grok + the date filter │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the port 9200 │
│ ▼ │
│ The Elasticsearch: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the docker-logs-YYYY.MM.dd indices │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the port 5601 │
│ ▼ │
│ The Kibana: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the search and the visualization │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
The Loki Pipeline
┌──────────────────────────────────────────────────────────────┐
│ THE LOKI PIPELINE │
│ │
│ The container: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ stdout / stderr │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the json-file driver │
│ ▼ │
│ The Docker host: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ /var/lib/docker/containers/*/*.log │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the Promtail + the docker socket │
│ ▼ │
│ The Promtail: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the docker_sd_configs + the labels │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the port 3100 │
│ ▼ │
│ The Loki: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the labels-only index + the chunks │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ │ the port 3000 │
│ ▼ │
│ The Grafana: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ the LogQL queries + the dashboards │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
The ELK vs the Loki
┌──────────────────────────────────────────────────────────────┐
│ THE ELK vs THE LOKI │
│ │
│ THE ELK: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ The full-text index │ │
│ │ The heavy: the Elasticsearch + the Logstash │ │
│ │ The RAM: the 2-4 GB for the ES, the 256-1 GB for │ │
│ │ the LS │ │
│ │ The powerful queries and the aggregations │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ THE LOKI: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ The labels-only index │ │
│ │ The lightweight: the Promtail + the Loki │ │
│ │ The RAM: the 512 MB for the Loki │ │
│ │ The grep-like queries, the cheap storage │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ The ELK is the powerful, and the Loki is the cheap. │
│ │
└──────────────────────────────────────────────────────────────┘
The Docker Socket
┌──────────────────────────────────────────────────────────────┐
│ THE DOCKER SOCKET │
│ │
│ The Promtail: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ volumes: │ │
│ │ - /var/run/docker.sock:/var/run/docker.sock │ │
│ │ │ │
│ │ The Promtail discovers the containers via the │ │
│ │ Docker socket and reads the metadata. │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ The Filebeat: │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ volumes: │ │
│ │ - /var/lib/docker/containers:/var/lib/docker/ │ │
│ │ containers:ro │ │
│ │ - /var/run/docker.sock:/var/run/docker.sock:ro │ │
│ │ │ │
│ │ The Filebeat reads the log files and uses the │ │
│ │ socket for the metadata. │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| The ELK | The Filebeat, the Logstash, the Elasticsearch, the Kibana |
| The Loki | The Promtail, the Loki, the Grafana |
| The Filebeat | The log shipper |
| The Logstash | The parser |
| The Elasticsearch | The store |
| The Kibana | The visualization |
| The Promtail | The log shipper |
| The Loki | The store |
| The Grafana | The visualization |
| The LogQL | The Loki query language |
| The docker socket | The metadata |
Key takeaways:
- The centralized log aggregation ships the container logs to the central system for the search and the analysis. The ELK uses the Filebeat, the Logstash, the Elasticsearch, and the Kibana. The Loki uses the Promtail, the Loki, and the Grafana .
- The Filebeat reads the Docker logs from the
/var/lib/docker/containers/and the Logstash parses them. Theautodiscoverdetects the new containers, and theadd_docker_metadataenriches the logs . - The Promtail discovers the containers via the Docker socket and pushes the logs to the Loki. The
docker_sd_configsand therelabel_configsextract the container name as the label . - The Loki indexes only the labels, not the full text. The storage is the cheap, and the queries use the
|= "error"and the| json. - The ELK is the powerful and the heavy, and the Loki is the lightweight and the cloud-native. The Elasticsearch needs the 2-4 GB of the RAM, and the Loki needs the 512 MB .
- The container labels route the logs to the different pipelines. The
filebeat_ingest: 'true'enables the ingestion, and thelogging=promtailenables the Promtail . - The Docker socket is the requirement for the metadata. The Promtail and the Filebeat mount the
/var/run/docker.sockto query the container metadata . - The Kafka buffers the high-throughput pipeline. The Filebeat sends the logs to the Kafka, and the Logstash reads from the Kafka, which provides the buffering and the replay .
Remember: The centralized log aggregation solves the multi-container problem by shipping the logs to the central system. The ELK is the powerful and the heavy, and the Loki is the lightweight and the cloud-native. The Filebeat and the Promtail are the log shippers, and the Docker socket provides the metadata. The Loki indexes the labels only, and the Grafana queries with the LogQL. The result is the searchable, the centralized, and the observable logs, which is the foundation of the container operations.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!