Managing disk space on servers running Docker containers can be challenging, especially when large log files consume significant space. This post provides a Bash script to truncate Docker log files larger than 100 MB when daemon.json cannot be reconfigured for log rotation and limits.
Prerequisites
- A Linux-based system
- Docker installed and running
- Permission to access and modify Docker log files
Script
#!/bin/bash
logs=$(du -k /var/lib/docker/containers/**/*-json.log | sort -hr)
while IFS= read -r line; do
size=$(echo $line | awk '{print $1}')
filepath=$(echo $line | awk '{print $2}')
if [ "$size" -gt 102400 ]; then
echo "Truncating $filepath (Size: $size KB)"
> "$filepath"
fi
done <<< "$logs"
echo "Log truncation complete."
Using the script
Make the script executable and run it:
chmod +x /root/truncate-docker-logs.sh
/root/truncate-docker-logs.sh
du -k reports usage in kilobytes, sort -hr orders the files by size, and the loop truncates only files above 102400 KB. Test the procedure in a safe environment before using it on a production host.
For a one-line alternative:
find /var/lib/docker/containers -name \*-json.log -size +100M -exec truncate -s 0 '{}' \;
If permissions prevent access, run the operation with appropriate elevated privileges. Verify the Docker log path for the host, because it can differ by installation.