14. Logging and Monitoring in Production
Seeing Inside Your Running Containers
In production, you cannot `docker exec` into every container to debug. You need centralized logging, metrics collection, and structured monitoring. This module covers logging drivers, log aggregation, and container metrics.
Logging Drivers: Where Logs Go
By default, Docker uses the `json-file` driver, which writes container logs to JSON files on the host. For production, you should send logs to a centralized system. Docker supports many logging drivers: `fluentd`, `awslogs` (CloudWatch), `gelf` (Graylog), `splunk`, `journald` (systemd), and `loki` (Grafana). Configure the driver per container or globally in `daemon.json`. Always set log rotation limits to prevent logs from filling your disk — without limits, a chatty container can write gigabytes of logs and crash the host.
# Run container with Fluentd logging docker run --log-driver=fluentd --log-opt fluentd-address=localhost:24224 myapp # Run container with AWS CloudWatch logging docker run --log-driver=awslogs --log-opt awslogs-region=us-east-1 --log-opt awslogs-group=myapp myapp # Set global logging options in daemon.json { "log-driver": "json-file", "log-opts": { "max-size": "10m", "max-file": "3" } } # Check current logging driver docker inspect --format='{{.HostConfig.LogConfig.Type}}' container_name
Structured Logging in Applications
Plain text logs are hard to search and analyze. Structured logs (JSON format) are machine-parseable and work seamlessly with log aggregation tools like ELK, Loki, or Datadog. Your application should output logs as JSON lines (one JSON object per line). Include fields like `timestamp`, `level`, `message`, `service`, `request_id`, and `user_id`. This enables powerful queries like "show all ERROR logs for service api in the last hour from user_id 123". Never log sensitive data — passwords, tokens, or PII.
// Good: Structured JSON logging in Node.js const log = (level, message, context = {}) => { console.log(JSON.stringify({ timestamp: new Date().toISOString(), level, message, service: 'payment-api', ...context })); }; log('info', 'User logged in', { userId: 123, ip: '192.168.1.1' }); // Output: {"timestamp":"2024-01-15T10:30:00Z","level":"info","message":"User logged in","service":"payment-api","userId":123,"ip":"192.168.1.1"}
Resource Monitoring with docker stats
The `docker stats` command shows real-time CPU, memory, network, and disk I/O for running containers. In production, you should collect these metrics over time using Prometheus with cAdvisor or using a monitoring agent. Monitor memory usage against limits (containers getting close to limits may be OOM-killed). Monitor CPU usage — sustained high CPU may indicate inefficient code or the need for scaling. Monitor network I/O for traffic patterns.
# Real-time stats for all containers docker stats # Stats for specific container docker stats container_name # Format output for scripting docker stats --no-stream --format "table {{.Container}} {{.CPUPerc}} {{.MemUsage}}" # Prometheus + cAdvisor (collect metrics over time) docker run -d \ --name cadvisor \ --volume /:/rootfs:ro \ --volume /var/run:/var/run:ro \ --volume /sys:/sys:ro \ --volume /var/lib/docker/:/var/lib/docker:ro \ --publish 8080:8080 \ gcr.io/cadvisor/cadvisor # Then add Prometheus to scrape http://localhost:8080/metrics
Knowledge Check
Ready to test your understanding of 14. Logging and Monitoring in Production?