Automating Ubuntu System Maintenance with Cron Jobs
DEV Community

Automating Ubuntu System Maintenance with Cron Jobs

Prerequisites

  • Operating System: Ubuntu
  • User: admin (sudo privileges)
  • Docker: Installed (optional)
  • Scripts Directory: /home/admin/linux/scripts

Step 1: Create a Directory for Scripts

Create a dedicated directory to organize your Linux administration scripts.

mkdir -p /home/admin/linux/scripts

Step 2: Create the Maintenance Script

Create the script.

touch /home/admin/linux/scripts/system_maintenance.sh
chmod +x /home/admin/linux/scripts/system_maintenance.sh

Open the file and paste the following:

#!/bin/bash
set -euo pipefail

LOG_FILE="/var/log/system_maintenance.log"
LOCK_FILE="/tmp/system_maintenance.lock"

exec 200>"$LOCK_FILE"
flock -n 200 || exit 1

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

log "========== Starting system maintenance =========="
log "Updating package lists..."
sudo apt update

log "Upgrading installed packages..."
sudo apt upgrade -y

log "Removing unused packages..."
sudo apt autoremove -y

log "Cleaning APT cache..."
sudo apt autoclean -y

if command -v docker >/dev/null 2>&1; then
    log "Cleaning Docker resources..."
    sudo docker system prune -af --volumes
fi

log "========== System maintenance completed =========="

Understanding the Script

Enable Safe Bash Options

set -euo pipefail - These options make the script more reliable.

  • -e - Exit immediately if a command fails.
  • -u - Treat undefined variables as errors.
  • pipefail - Detect failures inside pipelines.

Prevent Multiple Executions

LOCK_FILE="/tmp/system_maintenance.lock"
exec 200>"$LOCK_FILE"
flock -n 200 || exit 1

If the previous maintenance job is still running, another instance will not start. This prevents:

  • duplicate updates
  • package manager conflicts
  • simultaneous Docker cleanup

Update Ubuntu Packages

sudo apt update
sudo apt upgrade -y

These commands:

  • Refresh package indexes.
  • Install all available updates automatically.

Remove Unused Packages

sudo apt autoremove -y

Removes packages that are no longer required by the system.

Clean the APT Cache

sudo apt autoclean -y

Deletes obsolete package files from the local package cache to reclaim disk space.

Clean Docker Resources

sudo docker system prune -af --volumes

This removes unused Docker resources, including:

  • stopped containers
  • dangling images
  • unused images
  • unused networks
  • build cache
  • unused volumes

Note: Running containers and resources currently in use are not removed.

Step 3: Create the Log File

Since /var/log is owned by root, create the log file once:

sudo touch /var/log/system_maintenance.log
sudo chown admin:admin /var/log/system_maintenance.log

Example output:

[2026-07-22 01:00:00] Starting system maintenance
[2026-07-22 01:00:01] Updating package lists...
[2026-07-22 01:00:45] Upgrading installed packages...
[2026-07-22 01:01:10] Removing unused packages...
[2026-07-22 01:01:25] Cleaning APT cache...
[2026-07-22 01:01:40] Cleaning Docker resources...
[2026-07-22 01:01:55] System maintenance completed.

Step 4: Configure Passwordless sudo

Cron jobs cannot respond to password prompts. Edit the sudoers file:

sudo visudo

Add the following line:

admin ALL=(ALL) NOPASSWD: /usr/bin/apt, /usr/bin/docker

This allows the admin user to execute only the required commands without entering a password.

Step 5: Schedule the Cron Job

Open your crontab.

crontab -e

Add the following entry:

0 1 * * * /home/admin/linux/scripts/system_maintenance.sh >> /var/log/system_maintenance.log 2>&1

This runs the maintenance script every day at 1:00 AM. Check created cronjob:

crontab -l

Testing the Script

Before relying on cron, execute the script manually.

/home/admin/linux/scripts/system_maintenance.sh

Recommended Directory Structure

Keeping administration scripts organized makes long-term maintenance easier.

/home/admin/linux/
โ”œโ”€โ”€ scripts/
โ”‚   โ”œโ”€โ”€ system_maintenance.sh
โ”‚   โ”œโ”€โ”€ backup.sh
โ”‚   โ”œโ”€โ”€ docker_cleanup.sh
โ”‚   โ””โ”€โ”€ ssl_renew.sh
โ”œโ”€โ”€ logs/
โ””โ”€โ”€ configs/

Maintenance Tasks Performed

Task Command
Update package lists sudo apt update
Upgrade packages sudo apt upgrade -y
Remove unused packages sudo apt autoremove -y
Clean package cache sudo apt autoclean -y
Clean Docker resources sudo docker system prune -af --volumes

Conclusion

Automating routine maintenance with cron is an easy way to keep your Ubuntu server secure, efficient, and free from unnecessary disk usage. By combining package updates, cache cleanup, and Docker pruning into a single scheduled task, you reduce manual administration while ensuring your system stays in good condition. Review the maintenance logs periodically, monitor available disk space, and adjust the schedule as needed to match your server's workload.

Comments

No comments yet. Start the discussion.