Docker Logs and Resource Limits: Monitoring Containers in Practice

Docker resource limits and logging: set memory and CPU caps, avoid OOM kills and exit code 137, and watch containers with docker stats.

Executive Summary: Two defaults cause most operational surprises with Docker on a single host: container logs are written to JSON files with no size limit, and containers have no memory or CPU limits. The first eventually fills the disk; the second lets one leaking service take down every other service on the machine. Configure log rotation once in the daemon, log structured JSON to stdout, set memory and CPU limits on every container, learn to recognize an out-of-memory kill, and collect per-container metrics with cAdvisor and Prometheus or your platform’s equivalent.
Isometric container inside a glass limit box with memory and CPU gauges and a log terminal behind it

A small production server runs eight containers happily for five months. Then the disk fills up: one chatty service has written 38 GB of logs into a single JSON file under /var/lib/docker/containers. The next month, a memory leak in a reporting job grows until the Linux kernel’s OOM killer starts terminating processes, and it picks the database. Neither problem was exotic. Both were defaults nobody changed.

Logs: write to stdout, let Docker handle the rest

A container’s main process should write logs to standard output and standard error. Docker captures both streams and passes them to a logging driver. With the default json-file driver, they are stored on the host and read with docker logs, as introduced in your first container.

Log one JSON object per line rather than free text. Structured logs with consistent fields such as timestamp, level, message, request ID and service name are easy to filter on the host with jq and easy to index in any log platform.

{"ts":"2023-10-10T15:42:07Z","level":"error","msg":"payment declined","request_id":"7f3c","service":"billing-api","code":"card_expired"}

Rotate logs, once, for every container

The json-file driver does not rotate by default. Fix it host-wide in /etc/docker/daemon.json:

{
  "log-driver": "local",
  "log-opts": {
    "max-size": "20m",
    "max-file": "5"
  }
}

The local driver stores logs in a compact format with rotation and compression enabled by default; json-file with max-size and max-file also works. Restart the daemon after the change, and note that the setting applies only to containers created afterwards, so recreate existing ones. Per-container overrides use --log-opt or the logging key in Compose.

Shipping logs off the host

Logs on a single host disappear with the host. Common ways to centralize them:

  • A log agent such as Fluent Bit, Vector or the Grafana Agent reading the container log files and forwarding them to Loki, Elasticsearch or a SaaS platform. This keeps docker logs working and is the most common setup.
  • A logging driver that sends directly to a destination, such as awslogs for CloudWatch, gcplogs, journald or fluentd. Since Docker 20.10, “dual logging” keeps a local cache so docker logs still works with these drivers.

Resource limits: protect the neighbors

Without limits, a container can use all of the host’s memory and CPU. Docker enforces limits through cgroups:

docker run -d --name api \
  --memory 512m \
  --memory-reservation 384m \
  --cpus 1.5 \
  --pids-limit 300 \
  billing-api:1.8.0
Flag Effect
--memory Hard limit. Exceed it and the kernel kills a process in the container
--memory-reservation Soft limit the kernel tries to enforce when the host is under memory pressure
--memory-swap Memory plus swap; set equal to --memory to disable swap for the container
--cpus Maximum CPU time, for example 1.5 cores’ worth; excess usage is throttled, not killed
--cpu-shares Relative weight when CPUs are contended; no effect when CPU is free
--pids-limit Maximum number of processes and threads, which stops fork bombs

The key difference: running out of CPU makes a container slow, while running out of memory makes it die. Memory limits therefore need more headroom than CPU limits.

Recognizing an out-of-memory kill

docker ps -a --filter name=api       # STATUS shows "Exited (137)"
docker inspect api --format '{{.State.OOMKilled}} {{.State.ExitCode}}'
# true 137

Exit code 137 means the process received SIGKILL (128 + 9). Combined with OOMKilled: true, the container hit its memory limit. Exit code 137 without OOMKilled usually means something else killed it, such as docker kill or a stop that timed out.

Make the runtime aware of the limit

Language runtimes size their heaps from the memory they think is available. Modern ones read cgroup limits, but defaults vary:

  • Java has been container-aware since Java 10 (and 8u191). By default the maximum heap is a quarter of the limit; set -XX:MaxRAMPercentage=75 to use more of it.
  • Node.js sizes its old-generation heap from system memory in a way that does not always respect cgroup limits; set --max-old-space-size to about 75% of the container’s limit, in megabytes.
  • Go 1.19 and later support a soft memory limit with the GOMEMLIMIT environment variable; set it a little below the container limit so the garbage collector works harder before the kernel steps in.
  • Python has no heap limit setting; watch worker counts, since each Gunicorn worker is a separate process with its own memory.

Choosing the numbers

Run the service under realistic load without limits in a test environment, watch its peak memory and CPU with docker stats, then set the memory limit to peak plus 25 to 50 percent and the CPU limit to what keeps latency acceptable. Revisit after major changes. A limit that is too tight causes restarts; no limit at all causes outages for everyone else.

Monitoring containers

docker stats                                   # live CPU, memory, network and I/O per container
docker events --filter type=container          # starts, stops, kills, OOMs and health changes as they happen
docker inspect --format '{{json .State.Health}}' api | jq   # recent healthcheck results

docker stats and docker events are excellent for a quick look. For history and alerting, collect metrics continuously. The standard open-source setup is cAdvisor, which exposes per-container CPU, memory, network and filesystem metrics, scraped by Prometheus and graphed in Grafana, with Node Exporter for host-level metrics. Alerts worth having from day one:

  • Container memory above 90% of its limit for several minutes.
  • Any OOM kill or a container restarting repeatedly.
  • CPU throttling sustained over a meaningful share of periods, which shows up as latency before anything breaks.
  • Host disk usage above 80%, because logs, images and volumes all share it.

Application-level metrics, such as request rates, error rates and latency, come from the application itself, usually through a Prometheus client library or OpenTelemetry. Container metrics tell you a service is struggling; application metrics tell you why.

Frequently Asked Questions

Where are Docker container logs stored?

With the default json-file driver on Linux, under /var/lib/docker/containers/CONTAINER_ID/ as JSON files. Read them with docker logs rather than directly, and configure rotation so they do not grow without limit.

How do I stop Docker logs from filling the disk?

Set log rotation in /etc/docker/daemon.json, either the local driver or json-file with max-size and max-file options, restart the daemon and recreate containers so they pick up the setting.

What does exit code 137 mean in Docker?

The process was killed with SIGKILL. If docker inspect shows OOMKilled as true, the container exceeded its memory limit. Otherwise it was killed by another source, such as docker kill or a stop timeout.

Should every container have a memory limit?

Yes, on shared hosts. Without a limit, a single memory leak can exhaust host memory and cause the kernel to kill unrelated processes. Set limits with headroom above measured peak usage and configure the language runtime to respect them.

Bounded logs, bounded resources

Running containers well on a single host is mostly about putting limits on things that grow: log files, memory, CPU and process counts. Configure rotation and limits once in your templates, teach the runtime what its limit is, and collect metrics before you need them. The same ideas reappear as requests and limits in Kubernetes, so the habits transfer directly. The official documentation is worth keeping open: the resource constraints documentation and the Docker logging documentation. Related reading on this site: namespaces and cgroups and debugging common failures.

Originally posted on 12 October 2023 and post last modified on 12 October 2023

DevOps Docker Logging Observability

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *