A threshold-gated linux disk cleanup script prevents silent root-partition exhaustion on production VPS hosts before PostgreSQL refuses writes, Docker containers stall, or SSH logins fail. Most Linux servers do not run out of disk space from application data alone; they fill up gradually from orphaned Docker build caches, dangling container images, unrotated systemd journal binaries, and stale package caches. Running an aggressive docker system prune -af blindly on a cron job is equally risky because it wipes recent rollback layers and slows down your next deployment. Built for Ubuntu 22.04+, Debian 12+, and RHEL 9+ servers running Python 3.10+, the script below measures mount utilization, triggers cleanup only when usage crosses your configured percentage threshold, prunes Docker artifacts older than a safe retention window, vacuums systemd-journald logs, clears stale temporary files, supports a non-destructive --dry-run flag, and sends before-and-after Slack or Discord webhook summaries.
Key Takeaways & Script Specs
- Runtime & Dependencies: Python 3.10+ standard library (
shutil,subprocess,fcntl,pathlib) plus optionalrequestsfor webhook alerts. - Cleanup Targets: Docker build cache, dangling/old images (
until=72h),systemd-journaldarchives, APT/DNF caches, and aged/tmpfiles. - Safety Controls: Threshold gating (default 80% used), single-instance
flocklockfile, volume-safe Docker pruning (never deletes named volumes), and--dry-runsimulation. - Observability: Emits structured terminal or
--jsonreports showing reclaimed gigabytes and sends Slack/Discord notifications on cleanup runs.
Table of Contents
Why Linux Root Partitions Fill Up Silently in 2027
On modern containerized Linux servers, disk bloat comes from three invisible accumulators rather than user uploads. First, Docker BuildKit caches intermediate build layers, multi-arch manifests, and exited CI containers after every deployment. Over a few weeks of automated releases, /var/lib/docker/overlay2 can quietly consume 30 to 60 GB even when only four containers are running. Second, systemd-journald defaults to using up to 10% of the underlying filesystem (capped at 4 GB) in /var/log/journal, which adds significant pressure on compact 40 GB or 80 GB cloud NVMe volumes.
Third, package managers and temporary directories accumulate orphaned .deb archives, old kernel headers, and abandoned build artifacts in /tmp. Simply running docker system prune -a without time filters removes every stopped container and every image not currently referenced by a running container—destroying your ability to roll back to yesterday’s release in seconds. As documented in the official Docker system prune CLI reference, pairing prune commands with an --filter "until=72h" duration preserves recent rollback artifacts while still reclaiming stale layers.
Architecture and Threshold-Gated Cleanup Flow
Instead of deleting caches on a fixed nightly schedule regardless of free space, our script behaves like a thermostat. It checks actual filesystem utilization first, acquires a non-blocking file lock so overlapping runs cannot collide, and executes only the safe, time-bounded reclaimers you enable:
+-------------------------------------------------------------------+
| 1. Acquire Exclusive Lock (/run/lock/disk_cleanup.lock) |
|---|
|
v
+-------------------------------------------------------------------+
| 2. Measure Mount Usage via shutil.disk_usage(mount_path) |
| - Usage < --threshold (80%) and not --force? -> Exit 0 cleanly|
+---------------------------------+---------------------------------+
| (Threshold Breached or --force)
v
+-------------------------------------------------------------------+
| 3. Execute Safe Reclaimers (or log [DRY-RUN] commands) |
| - Docker: container/image/builder prune --filter until=72h |
| - Journald: journalctl --vacuum-time=14d --vacuum-size=500M |
| - APT/DNF: apt-get clean / dnf clean all (if available) |
| - Temp: age-bounded cleanup of /tmp files older than 7 days |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 4. Re-measure Disk Free Space + Send Before/After Webhook Alert |
+-------------------------------------------------------------------+
This defensive design pairs naturally with your existing server automation stack. While your automated Linux server backup script protects database dumps and configs offsite, and your Nginx log analyzer script watches access-log anomalies, this cleanup utility keeps local NVMe storage healthy without touching persistent Docker volumes or active application data.
Comparing Linux Disk Cleanup Strategies in 2027
Before installing a cleanup daemon, compare how the four common disk-maintenance approaches balance safety, rollback preservation, and observability.
| Cleanup Approach | Threshold Gated | Preserves Recent Docker Layers | Dry-Run & Reporting | Risk of Data Loss |
|---|---|---|---|---|
Raw docker system prune -af Cron | No (runs blindly) | No (deletes all unused) | None | Medium (wipes rollbacks) |
Manual ncdu / du Triage | Manual | Yes (human choice) | Interactive UI | Low |
logrotate + journald.conf Only | Size-capped only | Does not clean Docker | Logs only | Very Low |
| Python Threshold Cleanup Script | Yes (e.g. >= 80%) | Yes (until=72h filter) | --dry-run + Webhook | Very Low (volume-safe) |
Notice that interactive free developer CLI tools like ncdu or dust remain great for one-off forensic investigations when an unexpected directory balloons, whereas an automated threshold script handles routine build-cache and journal hygiene hands-free.
Prerequisites and Safe Configuration Rules
You can run the script using your system Python 3.10+ binary with zero third-party packages if you only want terminal or --json output. To enable Slack or Discord webhook alerts, create an isolated virtual environment and install requests:
sudo mkdir -p /opt/linux-disk-cleanup
sudo chown "$USER":"$USER" /opt/linux-disk-cleanup
cd /opt/linux-disk-cleanup
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install "requests>=2.32.0,<3.0.0"
Notice two critical safety rules baked into the design. First, the script never passes --volumes to docker system prune, as warned in the Docker resource pruning guide, so unattached database volumes are never accidentally destroyed. Second, it uses the official journalctl vacuum options (--vacuum-time and --vacuum-size) rather than deleting binary journal files with rm -rf, which prevents corrupting active systemd journal descriptors.
Complete Production Python Linux Disk Cleanup Script
Save the following script as /opt/linux-disk-cleanup/disk_cleanup.py. It measures filesystem usage in bytes, enforces a non-blocking fcntl.flock lockfile, safely skips missing tools (so it works whether or not Docker is installed), supports --dry-run and --force, and reports exact gigabytes reclaimed.
#!/usr/bin/env python3
"""
Production Linux Disk Cleanup Script (2027)
Monitors mount usage, triggers safe Docker (until=72h), journalctl vacuum,
package cache, and aged /tmp cleanup above threshold, with --dry-run & alerts.
"""
import argparse
import fcntl
import json
import logging
import os
import shutil
import socket
import subprocess
import sys
import time
from pathlib import Path
from typing import Dict, List, Optional
try:
import requests
except ImportError:
requests = None
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stdout,
)
logger = logging.getLogger("linux_disk_cleanup")
LOCK_PATH = Path("/tmp/linux_disk_cleanup.lock")
def get_disk_stats(mount_path: str) -> Dict[str, float]:
"""Return total, used, free GB and used percentage for a mount point."""
usage = shutil.disk_usage(mount_path)
gb = 1024 ** 3
used_pct = round((usage.used / usage.total) * 100.0, 2) if usage.total else 0.0
return {
"total_gb": round(usage.total / gb, 2),
"used_gb": round(usage.used / gb, 2),
"free_gb": round(usage.free / gb, 2),
"used_pct": used_pct,
}
def run_cmd(cmd: List[str], dry_run: bool, timeout: int = 180) -> Dict[str, object]:
"""Execute a cleanup command safely without shell=True."""
cmd_str = " ".join(cmd)
if dry_run:
logger.info("[DRY-RUN] Would execute: %s", cmd_str)
return {"command": cmd_str, "status": "dry-run"}
logger.info("Running: %s", cmd_str)
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
if proc.returncode == 0:
return {"command": cmd_str, "status": "ok"}
return {
"command": cmd_str,
"status": "error",
"exit_code": proc.returncode,
"stderr": proc.stderr.strip()[-300:],
}
except subprocess.TimeoutExpired:
return {"command": cmd_str, "status": "timeout"}
except OSError as exc:
return {"command": cmd_str, "status": "error", "stderr": str(exc)}
def clean_old_tmp_files(tmp_dir: Path, max_age_days: int, dry_run: bool) -> int:
"""Remove regular files in /tmp older than max_age_days without touching sockets."""
if not tmp_dir.is_dir():
return 0
cutoff = time.time() - (max_age_days * 86400)
removed = 0
for entry in tmp_dir.iterdir():
if entry.name.startswith("systemd-private-") or entry == LOCK_PATH:
continue
try:
if entry.is_symlink() or not entry.is_file():
continue
if entry.stat().st_mtime < cutoff:
if dry_run:
logger.info("[DRY-RUN] Would remove stale temp file: %s", entry)
else:
entry.unlink()
removed += 1
except OSError:
continue
return removed
def send_webhook(webhook_url: str, report: dict, dry_run: bool) -> None:
"""Post before-and-after cleanup summary to Slack or Discord."""
before = report["before"]
after = report["after"]
reclaimed = round(after["free_gb"] - before["free_gb"], 2)
host = socket.gethostname()
msg = (
f"*[Linux Disk Cleanup]* `{host}` (`{report['mount']}`)\n"
f"- Before: {before['used_pct']}% used ({before['free_gb']} GB free)\n"
f"- After: {after['used_pct']}% used ({after['free_gb']} GB free)\n"
f"- Reclaimed: {max(0.0, reclaimed)} GB | Stale tmp files: {report['tmp_files_removed']}"
)
if dry_run:
logger.info("[DRY-RUN] Would send webhook:\n%s", msg)
return
if requests is None:
logger.warning("Install 'requests' to enable webhook alerts.")
return
try:
resp = requests.post(webhook_url, json={"text": msg, "content": msg}, timeout=5)
resp.raise_for_status()
logger.info("Sent disk cleanup summary to webhook.")
except requests.RequestException as exc:
logger.error("Webhook delivery failed: %s", exc)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Threshold-gated Linux disk cleanup for Docker, journald, APT, and /tmp."
)
parser.add_argument(
"--mount",
default=os.getenv("CLEANUP_MOUNT", "/"),
help="Filesystem mount point to monitor (default: /)",
)
parser.add_argument(
"--threshold",
type=float,
default=float(os.getenv("CLEANUP_THRESHOLD", "80.0")),
help="Trigger cleanup when disk usage % meets or exceeds this value (default: 80.0)",
)
parser.add_argument(
"--docker-until",
default=os.getenv("DOCKER_PRUNE_UNTIL", "72h"),
help="Preserve Docker artifacts newer than this duration (default: 72h)",
)
parser.add_argument(
"--journal-time",
default=os.getenv("JOURNAL_VACUUM_TIME", "14d"),
help="Retain systemd journal entries within this timespan (default: 14d)",
)
parser.add_argument(
"--journal-size",
default=os.getenv("JOURNAL_VACUUM_SIZE", "500M"),
help="Cap archived systemd journal size (default: 500M)",
)
parser.add_argument(
"--tmp-days",
type=int,
default=int(os.getenv("TMP_MAX_DAYS", "7")),
help="Delete regular files in /tmp older than N days (default: 7)",
)
parser.add_argument(
"--force",
action="store_true",
help="Run cleanup immediately even if usage is below --threshold",
)
parser.add_argument("--json", action="store_true", help="Print JSON summary to stdout")
parser.add_argument(
"--dry-run",
action="store_true",
help="Simulate cleanup commands and print reclaimed estimate without deleting anything",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
lock_file = LOCK_PATH.open("w", encoding="utf-8")
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
logger.warning("Another disk cleanup instance is already running. Exiting.")
return 0
before = get_disk_stats(args.mount)
logger.info(
"Mount '%s' usage: %.2f%% (%s GB free / %s GB total)",
args.mount,
befor
e["used_pct"],
before["free_gb"],
before["total_gb"],
)
if before["used_pct"] < args.threshold and not args.force:
logger.info("Usage below %.1f%% threshold. No cleanup needed.", args.threshold)
return 0
actions = []
if shutil.which("docker"):
actions.append(
run_cmd(
["docker", "container", "prune", "-f", "--filter", f"until={args.docker_until}"],
args.dry_run,
)
)
actions.append(
run_cmd(
["docker", "image", "prune", "-af", "--filter", f"until={args.docker_until}"],
args.dry_run,
)
)
actions.append(
run_cmd(
["docker", "builder", "prune", "-af", "--filter", f"until={args.docker_until}"],
args.dry_run,
)
)
if shutil.which("journalctl"):
actions.append(
run_cmd(["journalctl", f"--vacuum-time={args.journal_time}"], args.dry_run)
)
actions.append(
run_cmd(["journalctl", f"--vacuum-size={args.journal_size}"], args.dry_run)
)
if shutil.which("apt-get"):
actions.append(run_cmd(["apt-get", "clean"], args.dry_run))
elif shutil.which("dnf"):
actions.append(run_cmd(["dnf", "clean", "all"], args.dry_run))
tmp_removed = clean_old_tmp_files(Path("/tmp"), args.tmp_days, args.dry_run)
after = get_disk_stats(args.mount)
report = {
"mount": args.mount,
"threshold_pct": args.threshold,
"dry_run": args.dry_run,
"before": before,
"after": after,
"tmp_files_removed": tmp_removed,
"actions": actions,
}
if args.json:
print(json.dumps(report, indent=2))
else:
reclaimed = round(after["free_gb"] - before["free_gb"], 2)
logger.info(
"Cleanup finished. Free space: %.2f GB -> %.2f GB (reclaimed %.2f GB)",
before["free_gb"],
after["free_gb"],
max(0.0, reclaimed),
)
webhook_url = os.getenv("WEBHOOK_URL")
if webhook_url:
send_webhook(webhook_url, report, dry_run=args.dry_run)
return 0
if name == "main":
sys.exit(main())
Before enabling automated runs, test the script safely with --force --dry-run so it prints every Docker, journalctl, and /tmp action without deleting a single byte:
chmod +x /opt/linux-disk-cleanup/disk_cleanup.py
sudo /opt/linux-disk-cleanup/.venv/bin/python /opt/linux-disk-cleanup/disk_cleanup.py --force --dry-run
Scheduling With a Systemd Timer or Cron
A daily systemd timer at 03:30 AM keeps your servers clean while capturing stdout directly in the system journal. Store your WEBHOOK_URL in a 0600 environment file and create both the oneshot service and timer units:
cat <<'EOF' > /opt/linux-disk-cleanup/.env
CLEANUP_THRESHOLD=80.0
DOCKER_PRUNE_UNTIL=72h
JOURNAL_VACUUM_TIME=14d
WEBHOOK_URL=https://hooks.slack.com/services/REPLACE/ME/NOW
EOF
chmod 600 /opt/linux-disk-cleanup/.env
sudo tee /etc/systemd/system/linux-disk-cleanup.service >/dev/null <<'EOF'
[Unit]
Description=Threshold-Gated Linux Disk Cleanup
After=docker.service
[Service]
Type=oneshot
EnvironmentFile=/opt/linux-disk-cleanup/.env
ExecStart=/opt/linux-disk-cleanup/.venv/bin/python /opt/linux-disk-cleanup/disk_cleanup.py
EOF
sudo tee /etc/systemd/system/linux-disk-cleanup.timer >/dev/null <<'EOF'
[Unit]
Description=Run Linux Disk Cleanup Daily at 03:30 AM
[Timer]
OnCalendar=--* 03:30:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now linux-disk-cleanup.timer
Pairing this timer with a Docker health check script ensures your containers stay both healthy and disk-safe around the clock.
Troubleshooting and Security Hardening
Watch for these three operational edge cases when deploying disk cleanup across production Linux fleets:
- Docker Prune Permission Errors: Running
docker pruneandjournalctl --vacuum-*requires eitherroot(via a root-ownedsystemdunit) or membership in thedockerandadmgroups. Keep the script file owned byroot:rootwith0750permissions when invoked by a root systemd timer so non-privileged users cannot modify it. - Preserving Active
/tmpSockets: Never delete directories or Unix domain sockets inside/tmpblindly—doing so can break running X11, MySQL, or systemd private temp namespaces. The script explicitly skips directories, symlinks, andsystemd-private-*entries. - Large Database Rollback Images: If your team keeps blue-green container images on disk for more than three days, raise
--docker-until 168h(7 days) so recent tagged images remain cached locally.
Frequently Asked Questions
Will this Linux disk cleanup script delete my Docker database volumes?
No. The script prunes only exited containers, unused images, and build cache older than –docker-until (default 72h). It never calls docker volume prune, so named and anonymous database volumes remain untouched.
Why does the script check a threshold before pruning?
Threshold gating (default 80% disk usage) avoids wiping your Docker BuildKit cache every night when your disk has plenty of free space, keeping CI builds and container restarts fast.
How can I test what will be deleted before running it in production?
Pass –force –dry-run on the command line. The script logs every Docker, journalctl, package-cache, and /tmp action it would take without deleting any files.
Does it work on servers that do not have Docker installed?
Yes. The script checks shutil.which(‘docker’), shutil.which(‘journalctl’), and package managers dynamically, safely skipping any tool not present on the host.
Is it safe to clean /tmp automatically?
Yes, when restricted to regular files older than 7 days while skipping directories, symlinks, sockets, and systemd-private-* folders, as implemented in clean_old_tmp_files().
Can I monitor /var or a separate mount point instead of root (/)?
Yes. Pass –mount /var (or set CLEANUP_MOUNT=/var in your .env file) to evaluate threshold usage on that specific partition.