LazyCodet

a

15:16:14 3/6/2025 - 2 views -
Programming

How to Clean Up Disk Space on Ubuntu: A Comprehensive Guide

​Managing disk space on an Ubuntu server or desktop is essential to maintain performance and avoid storage issues. Over time, logs, caches, old packages, and temporary files can accumulate, consuming significant disk space. This blog provides a step-by-step guide to safely and effectively clean up unnecessary data on Ubuntu, helping you reclaim valuable storage.

Why Clean Up Disk Space?

Disk space can fill up due to:

  • System logs: Logs from services like systemd, Apache, or databases.

  • Package cache: Leftover .deb files from apt installations.

  • Old kernels: Unused Linux kernel versions in /boot.

  • Temporary files: Data in /tmp or user caches.

  • Unused software: Packages or Snap applications no longer needed.

By identifying and removing these, you can free up gigabytes of space. Below are practical methods to analyze and clean your Ubuntu system.


Step 1: Check Disk Usage

Before cleaning, identify which directories are consuming the most space:

df -h

This displays disk usage in a human-readable format. To dive deeper into specific directories:

sudo du -sh /* | sort -hr

Example Output:

6.9G    /usr
5.3G    /var
1.7G    /snap
1.6G    /root
263M    /boot
255M    /home

Focus on large directories like /var, /usr, and /snap for cleanup.


Step 2: Clean Up Package Cache

Ubuntu’s package manager (apt) stores downloaded .deb files in /var/cache/apt/archives/, which can grow large.

2.1. Remove Obsolete Package Files

Run:

sudo apt autoclean
  • What it does: Removes .deb files for packages no longer available in the repository.

  • Safety: Completely safe; it only deletes outdated cache files.

2.2. Clear All Package Cache

To remove all cached .deb files:

sudo apt clean
  • What it does: Deletes all files in /var/cache/apt/archives/.

  • Note: Safe, but keep in mind you’ll need to re-download packages for reinstallation.

2.3. Check Cache Size

Before and after cleaning, check the cache size:

du -sh /var/cache/apt/archives/

Example: Reducing from 500MB to 50MB after autoclean.


Step 3: Remove Unneeded Packages

Packages and their dependencies can linger after software is removed.

3.1. Use autoremove

Run:

sudo apt autoremove
  • What it does: Removes packages automatically installed as dependencies but no longer needed.

  • Safety: Generally safe, but check the list of packages to be removed first:

    sudo apt autoremove --dry-run

Example: This might remove old kernel images or unused libraries, saving hundreds of MB.

3.2. Check Package Sizes

To see the largest installed packages:

dpkg-query -W -f='${Installed-Size;8}  ${Package}\n' | sort -nr | head -n 10

Remove unnecessary ones with:

sudo apt remove 
​

Step 4: Clean Up System Logs

Logs in /var/log can grow significantly, especially for servers running services like Apache or Elasticsearch.

4.1. Check Log Sizes

List log sizes:

sudo du -sh /var/log/* | sort -hr

Example Output:

2.0G    /var/log/journal
18M     /var/log/elasticsearch
5.2M    /var/log/apache2

4.2. Clean systemd Journal Logs

The /var/log/journal directory stores systemd logs, which can balloon to gigabytes.

  • Limit by time (keep last 7 days):

    sudo journalctl --vacuum-time=7d
  • Limit by size (keep 500MB):

    sudo journalctl --vacuum-size=500M
  • Permanent limit: Edit /etc/systemd/journald.conf:

    [Journal]
    SystemMaxUse=500M
    SystemKeepFree=1G

    Apply changes:

    sudo systemctl restart systemd-journald

4.3. Clear Other Logs

For other logs (e.g., /var/log/apache2, /var/log/syslog):

  • Truncate large logs:

    sudo truncate -s 0 /var/log/apache2/access.log
  • Compress old logs:

    sudo find /var/log -type f -name "*.log" -exec gzip {} \;
  • Check before deleting:

    sudo du -sh /var/log/*

Step 5: Manage Snap Packages

Snap packages (in /snap) can consume significant space due to multiple versions.

5.1. List Snap Packages

Check installed Snaps:

snap list

5.2. Remove Unused Snaps

Remove unnecessary Snap packages:

sudo snap remove 
​

5.3. Clean Old Snap Versions

Snap keeps old versions. Limit to two versions:

sudo snap set system refresh.retain=2

Remove disabled versions:

sudo sh -c 'snap list --all | awk "/disabled/{print \$1, \$3}" | while read snapname revision; do snap remove "$snapname" --revision="$revision"; done'

Step 6: Clean Up Old Kernels

Old kernel images in /boot can accumulate, especially after system updates.

6.1. Check Kernels

List installed kernels:

dpkg --list | grep linux-image

Check the current kernel:

uname -r

6.2. Remove Old Kernels

Use:

sudo apt autoremove --purge

Or manually remove specific kernels:

sudo apt purge linux-image-
​

Note: Keep the current kernel and at least one backup kernel.


Step 7: Clear Temporary Files

Temporary files in /tmp and /var/tmp can be safely deleted.

sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*

Note: Ensure no critical processes are using these files before deletion.


Step 8: Find Large Files

To locate large files across the system:

sudo find / -type f -size +100M

Review and delete unnecessary files:

sudo rm /path/to/large/file

Step 9: Use Graphical Tools

For a user-friendly approach, install tools like:

  • Disk Usage Analyzer (Baobab):

    sudo apt install baobab
    baobab
  • ncdu (terminal-based):

    sudo apt install ncdu
    ncdu /

These tools provide a visual overview of disk usage.


Step 10: Automate Cleanup

To prevent future disk space issues, automate cleanup tasks:

  • Limit journal logs: Set SystemMaxUse=500M in /etc/systemd/journald.conf.

  • Schedule cleanup: Add a cron job to clean logs and cache:

    sudo crontab -e

    Add:

    0 0 * * 0 /usr/bin/apt autoremove --purge && /usr/bin/apt autoclean && /usr/bin/journalctl --vacuum-size=500M

    This runs weekly to clean packages and logs.


Visualizing Disk Usage

To visualize the impact of cleanup, you can create a bar chart. Here’s an example Chart.js configuration based on sample data:

{
  "type": "bar",
  "data": {
    "labels": ["Before Cleanup", "After Cleanup"],
    "datasets": [{
      "label": "Disk Usage (GB)",
      "data": [15.2, 10.5],
      "backgroundColor": ["#FF6384", "#36A2EB"],
      "borderColor": ["#FF6384", "#36A2EB"],
      "borderWidth": 1
    }]
  },
  "options": {
    "scales": {
      "y": {
        "beginAtZero": true,
        "title": {
          "display": true,
          "text": "Disk Usage (GB)"
        }
      },
      "x": {
        "title": {
          "display": true,
          "text": "State"
        }
      }
    },
    "plugins": {
      "legend": {
        "display": false
      },
      "title": {
        "display": true,
        "text": "Disk Usage Before and After Cleanup"
      }
    }
  }
}

Conclusion

By following these steps, you can reclaim significant disk space on your Ubuntu system. Start with apt autoremove and autoclean for package cleanup, then tackle large logs in /var/log/journal and manage Snap packages or old kernels. Always verify before deleting critical files, and use tools like ncdu or Baobab for a visual overview. Automating cleanup tasks ensures your system stays lean in the long term.

For ongoing maintenance, regularly check disk usage with df -h and du. If you need help analyzing specific directories or automating tasks, feel free to dive deeper into any section!