Two problems often come up together when troubleshooting Docker logs. Logs keep growing until the host disk fills up. Or you try to export them to a file, only to find the terminal still printing lines that are missing from the file. The first calls for checking logging drivers and retention. The second requires understanding standard output, standard error and shell redirection.
One example from Viewing and Cleaning Up Docker Container Logs is particularly vivid. On a 200 GB disk, the containers directory used about 181 GB and a single container directory accounted for about 180 GB. Those figures come from the article, not my server. Both the Zhihu article and a CSDN article about managing logs go from clearing logs to limiting their size. In practice, emergency disk recovery and long-term rotation call for different procedures.
This article focuses on Docker Engine on a Linux host. Docker Desktop keeps its data in a Linux environment it manages, and a remote Docker context points to another machine. In those cases a path returned by docker inspect cannot be treated as a path on your own machine.
Distinguish three types of logs
| Log type | Contents | Where it is managed |
|---|---|---|
| Container standard output and standard error | What the application writes to stdout and stderr | Docker logging driver, usually viewed via docker logs |
| Files written by the application | For example, app.log in an application directory | Application logging framework, mounted volume or application-specific rotation |
| Docker daemon logs | Runtime messages and errors from dockerd | Linux service logs such as the systemd journal |
docker logs does not search for every .log file in the container. When a program writes only to a regular file, its own logging configuration or a collector must handle it. Docker log size limits do not clean up that file. The official Nginx image links its access and error logs to stdout and stderr respectively, handing application logging over to the container logging mechanism. Docker logging overview
The notes on ClickHouse resource issues make the same distinction. Database log tables, application log files and Docker container logs each belong to a separate layer.
What problems do oversized logs cause?
The most immediate problem is running out of free space on the filesystem that holds the logs. Databases, applications and system services sharing that disk can lose the ability to write. Docker’s default json-file driver allows logs to grow continuously if rotation is disabled. Configuring logging drivers
Another issue is the cost of investigation. Reading, transferring and displaying an unlimited history consumes I/O, CPU and terminal processing time. A large log alone is insufficient evidence that Docker management commands must hang. Consider the write rate, disk performance, free space and current system load together. An ordinary tail -n 100 does not load the whole file into memory either.
Disk capacity and IOPS measure different things. A disk with ample free space can still respond slowly under heavy I/O, and a nearly full disk need not imply high CPU usage. To investigate historical resource use by process, see the monitoring techniques in troubleshooting an Alibaba Cloud server.
Limit the range before reading logs
Replace my-container below with the container name or ID:
# 最近 100 行
docker logs --tail 100 my-container
# 最近 30 分钟,并显示时间戳
docker logs --since 30m --timestamps my-container
# 先显示最后 100 行,再持续接收新输出
docker logs --tail 100 --follow my-container
# 按故障时间窗口导出,显式指定时区
docker logs --since '2026-11-13T10:00:00+08:00' \
--until '2026-11-13T10:15:00+08:00' --timestamps \
my-container > incident.log 2>&1
--tail defaults to all, so docker logs -f first reads existing history and then follows new output. -f does not mean “only from now on.” --since, --until and --tail limit the range read. They do not remove stored logs. docker logs reference
Why does the terminal keep printing after redirection?
The export command under discussion was:
docker logs -f 8bce > gongkard_log.txt
> captures only stdout. For a container started without a TTY and retaining two distinct streams, application logs sent to stderr may still appear in the terminal. Docker CLI errors can also go to stderr. This is neither “nested output” nor specific to -f. A container with a TTY may already have merged its streams, in which case client redirection cannot separate them again.
To save all the output:
docker logs --tail 100 -f 8bce > gongkard_log.txt 2>&1
To display and save it at the same time:
docker logs --tail 100 -f 8bce 2>&1 | tee gongkard_log.txt
2>&1 directs stderr to the current destination of stdout. tee writes its input to both the file and the terminal. 2>/dev/null discards stderr, so it cannot silently save the complete output. Bash redirections and GNU tee
The exported gongkard_log.txt is a new file outside Docker’s max-size and max-file limits. Running -f or tee -a indefinitely can make this copy grow without bound. For a short investigation, export a specific time range. For long-term retention, use a collection system with rotation and an expiry policy.
For more examples of pipes, separate output files and the order of redirections, see the redirection section in Linux Tools.
Locate disk usage and the actual log path
First confirm where Docker points and which driver it uses by default:
docker context show
docker info --format 'root={{.DockerRootDir}} default-driver={{.LoggingDriver}}'
docker ps -a --format 'table {{.ID}}\t{{.Names}}\t{{.Status}}'
Run these filesystem commands on the Linux host running the Docker daemon:
docker_root=$(docker info --format '{{.DockerRootDir}}')
df -h "$docker_root"
sudo du -h -x --max-depth=1 "$docker_root" | sort -h
sudo du -h -x --max-depth=1 "$docker_root/containers" | sort -h
df reports filesystem capacity. du counts space occupied by files it can traverse. -x stays on one filesystem and --max-depth=1 limits the displayed depth. These are GNU/Linux options. /var/lib/docker is common, but the data directory is configurable and may differ in rootless installations.
Once you have identified the container, check its own configuration as well as the daemon defaults:
container_name=my-container
docker inspect --format '{{json .HostConfig.LogConfig}}' "$container_name"
docker inspect --format '{{.LogPath}}' "$container_name"
Use the following check only after confirming that the container uses json-file:
log_path=$(docker inspect --format '{{.LogPath}}' "$container_name")
if [ -n "$log_path" ]; then
sudo ls -lh -- "$log_path"
sudo du -h -- "$log_path"
fi
This shows the active log file. Rotated files may occupy additional space, and directory totals also include other container metadata. Avoid assuming that every driver has a *-json.log, or constructing a path manually from a short ID. Inspecting logging drivers
Deal with logs that are already large
Why did rm fail to free the space?
On Linux, removing a filename unlinks its directory entry. If a process still holds the file open, the data may remain until the last relevant file descriptor is closed. That explains why du can stop seeing a deleted file while df still shows the space in use. Linux unlink manual
A Docker logging component may hold the log file. The application inside the container does not necessarily open the host’s JSON file directly. Restarting just the container is not guaranteed to release every handle to a deleted file.
Prefer the container lifecycle and rotation settings
If downtime can be scheduled, first save the incident logs you need. Configure rotation and recreate the target service. Recreation replaces the old container and its associated logs. Verify that persistent application data is in named volumes or bind mounts first. The writable container layer cannot serve as persistent storage. A single-instance service is unavailable during recreation.
One service does not require docker compose down for the entire project, particularly with options that delete volumes. The next section shows how to recreate only the target service. Compose up documentation
Reserve direct truncation for limited emergencies
The source article’s cat /dev/null > file truncates a file to zero bytes while preserving the filename. Docker explicitly states that the daemon manages these files and external modification may interfere with logging. Truncating a live log carries risks and should not be routine housekeeping. JSON File driver documentation
If the disk is full and space must be freed immediately, you can truncate one explicitly identified file after verifying the driver, host and actual path, provided you accept losing the container’s historical logs and potentially disrupting log reads. First export any required history somewhere with available space.
# 仅在上述应急条件成立时执行;沿用已核对的 log_path
sudo truncate -s 0 -- "$log_path"
df -h "$docker_root"
Avoid clearing *-json.log in bulk with a wildcard or putting this operation in a scheduled job. After truncation, configure rotation and check that logs can still be read. Otherwise they will soon grow again. sudo cat /dev/null > file can also fail on permissions: the current shell processes >, and sudo does not elevate that redirection.
Configure rotation and confirm it took effect
Limit one service in Compose
Put logging under the service definition at the same level as image and ports, outside deploy.resources. The following minimal example stands alone. For an existing service, keep the image, volumes, network and startup arguments and merge only the logging section. Compose logging configuration
services:
web:
image: nginx:stable
logging:
driver: json-file
options:
max-size: "100m"
max-file: "3"
max-size is the rotation threshold for one log file. max-file is the maximum file count including the active file. The example budgets around 300 MB of logs per container. It is not a hard quota for the entire container or filesystem. Multiply by the number of containers when deploying replicas. JSON File options
In the source article, 200m does not mean 200 KB. With 500m and max-file=3, the estimate is about 1.5 GB in total, rather than 500 MB. Also consider how much output is generated per second. At a fixed capacity, more frequent output leaves a shorter searchable history.
In the Compose project directory, after checking persistent data and scheduling the interruption, run:
docker compose config --quiet
docker compose up -d --no-deps --force-recreate web
docker compose ps -q web | while IFS= read -r container_id; do
docker inspect --format '{{.Name}} {{json .HostConfig.LogConfig}}' "$container_id"
done
web is the Compose service name. restart restarts an existing container with its original logging configuration. --force-recreate creates it again. Finally inspect each actual container and confirm its driver and options match the configuration. Compose up documentation
Specify the settings at creation with docker run
docker run -d --name log-demo \
--log-driver json-file \
--log-opt max-size=100m \
--log-opt max-file=3 \
nginx:stable
This example creates a new container. It cannot change an existing container in place.
Set global defaults
For a conventional Linux Docker Engine installation, merge the following keys into /etc/docker/daemon.json. Keep existing settings such as registry mirrors and storage paths. The file must be valid JSON, with no comments, missing commas or duplicate keys.
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "3"
}
}
Use strings for option values, including quotes around the number 3. Rootless Docker and Docker Desktop have different configuration entry points, so do not assume the system-level path applies. JSON File configuration
On a host using systemd, validate the change first. Once validation passes and the maintenance window is confirmed, restart Docker:
sudo dockerd --validate --config-file=/etc/docker/daemon.json
sudo systemctl restart docker
docker info --format '{{.LoggingDriver}}'
--validate checks the file without starting another daemon. Restarting the service may affect other containers on the host. Global defaults apply only to subsequently created containers. Existing containers still need recreation. Check service-specific overrides wherever a logging driver is explicitly configured. dockerd documentation and global logging configuration
Consider the local driver
When no collector depends on JSON format, consider local. It rotates and compresses logs by default. The defaults are 20 MB per file and up to five files, and compression further reduces actual disk usage. It also supports max-size and max-file, so those options are available beyond json-file. Local driver documentation
Check how the existing log collector works before switching. If an external system depends on the JSON file structure, the collection path must be accounted for in the change. For ordinary application log viewing, docker logs remains available.
What to check routinely
At deployment, choose the logging driver and capacity budget, then check the actual container settings. During operation monitor free filesystem capacity and the rate of log growth. When growth becomes unusual, investigate repeated errors, debug logging or changes in request volume.
Rotation controls how much history is retained. A sudden spike in log generation needs its own investigation. If you require long-term searches, cross-host analysis or more history than the host can store, forward the logs to centralized storage and configure retention there.
References
- 请叫我Longge. (n.d.). Viewing and Cleaning Up Docker Container Logs [Blog post]. Zhihu. The discussion uses the supplied article text, which identifies the CSDN article below as its original source.
- 我在北国不背锅. (n.d.). Viewing and Cleaning Up Docker Container Logs [Blog post]. CSDN. The original source and author are preserved as supplied. The material specifies CC BY-SA 4.0. This article reorganizes the explanation and corrects examples rather than reproducing the original in full.
- ajianboke. (n.d.). Methods for Viewing and Cleaning Up Docker Container Logs [Blog post]. CNBlogs. Further reference listed by the supplied article.
- 木山鱼. (n.d.). Oversized Docker Container Logs: Is There an Easier Solution? [Blog post]. CSDN. Retrieved November 13, 2026. The page specifies CC BY-SA 4.0. Its “latest recommendation” timestamp is not treated as the original publication date.
- Docker. (n.d.). View container logs. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). docker container logs. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). Configure logging drivers. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). JSON File logging driver. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). Local file logging driver. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). Define services in Docker Compose: logging. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). docker compose up. Docker Docs. Retrieved November 13, 2026.
- Docker. (n.d.). dockerd. Docker Docs. Retrieved November 13, 2026.
- Free Software Foundation. (n.d.). Redirections. GNU Bash Reference Manual.
- Free Software Foundation. (n.d.). tee: Redirect output to multiple files or processes. GNU Coreutils Manual.
- Linux man-pages project. (n.d.). unlink(2). Linux manual pages. Retrieved November 13, 2026.