Sub topic 6
Keeping Logs from Filling the Disk
This chapter assumes you can run containers with docker run, read output with docker logs, and edit a JSON file as an administrator. It covers the default logging driver, why its logs grow without limit, and how to cap them.
Why logs can fill a disk
The default json-file driver writes every line a container prints to a JSON file on the host, usually under /var/lib/docker/containers/<id>/. Without a limit, that file grows for as long as the container lives. A chatty service can use many gigabytes. When the disk is full, the Docker daemon, your databases, and the host itself can all fail.
Check which driver a container uses:
docker inspect --format '{{.HostConfig.LogConfig.Type}}' webThe output is json-file unless the daemon or the container was configured otherwise.
Rotation with max-size and max-file
Rotation keeps the log in a fixed number of files of limited size. Two options control it:
| Option | Meaning |
|---|---|
| `max-size` | Size at which the current log file is closed and a new one is started. Accepts `k`, `m`, or `g`, such as `10m`. |
| `max-file` | Number of log files to keep. When the limit is reached, the oldest file is deleted. |
Set them per container with --log-opt:
docker run -d --name web-rotated \
--log-driver json-file \
--log-opt max-size=10m \
--log-opt max-file=3 \
nginxThis container keeps at most three files of about 10 MB each, so roughly 30 MB. Older entries are discarded, and docker logs shows only what remains.
Setting a default for every container
Setting options on each docker run is easy to forget. Put the limits in the daemon configuration, normally /etc/docker/daemon.json:
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}Then restart the Docker daemon, for example with sudo systemctl restart docker.
Common errors
- Assuming the default is limited. With no configuration,
json-filehas no size limit. - Editing
daemon.jsonwithout restarting. The daemon reads the file at startup, so nothing changes until you restart it. - Invalid JSON in
daemon.json. A trailing comma or missing quote can stop the daemon from starting. Check the file before restarting. - Quoting numbers. Values in
log-optsmust be strings, such as"3", not3. - Expecting old logs to survive. Rotation deletes entries. If you need long-term history, send logs to a central system with another logging driver, or collect them with a log shipper.
Exercise
A container was created two weeks ago with no log options. You then add max-size and max-file to daemon.json and restart the daemon. Is the old container's log now limited? What should you do?
Show answer
No. Daemon defaults apply only to containers created after the restart, so the old container still has an unlimited json-file log. Remove and recreate the container, or create it with --log-opt max-size=10m --log-opt max-file=3, so it picks up the limits.