Docker logs auto delete script

Perfect idea πŸ’‘ β€” yes, you can absolutely automate log cleanup + prevention so you never run out of disk space again.

Below is a ready-to-use script that: βœ… Clears huge Docker logs safely βœ… Adds log rotation limits to /etc/docker/daemon.json βœ… Restarts Docker βœ… Sets up a cron job to run weekly (or daily, if you prefer)


🧰 Step 1: Create the script

Run this:

sudo tee /usr/local/bin/docker-log-cleanup.sh > /dev/null <<'EOF'
#!/bin/bash
# Docker log cleanup + prevention script
# Author: ChatGPT Automation
# Date: $(date)

LOG_LIMIT_SIZE="100m"
LOG_MAX_FILES="3"
DOCKER_CONFIG="/etc/docker/daemon.json"

echo "🧹 Truncating existing Docker logs..."
find /var/lib/docker/containers/ -type f -name "*.log" -exec truncate -s 0 {} \;

echo "βš™οΈ  Ensuring Docker log rotation policy..."
if [ -f "\$DOCKER_CONFIG" ]; then
    cp "\$DOCKER_CONFIG" "\${DOCKER_CONFIG}.bak_$(date +%F_%H-%M-%S)"
fi

cat > "\$DOCKER_CONFIG" <<JSON
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "$LOG_LIMIT_SIZE",
    "max-file": "$LOG_MAX_FILES"
  }
}
JSON

echo "πŸ” Restarting Docker to apply config..."
systemctl restart docker

echo "βœ… Docker log cleanup complete."
EOF

Then make it executable:


πŸ•’ Step 2: Automate with cron

Run:

Add this line at the bottom (for weekly cleanup, every Sunday at 2:00 AM):

If you want daily cleanup, use:


🧾 Step 3: Verify

You can test it manually first:

And check logs:


βœ… What this gives you

  • Automatic log trimming (safe, no data loss)

  • Docker configured to prevent future log bloat

  • A cron-based safety net that keeps your server healthy

Last updated