people space apple industry

Ways to free up disk space on Ubuntu Linux Servers

The commands in this article are commands I have found useful to figure out what’s taking up space on Linux servers and how to reclaim it.

Inspect Disk Usage

To find out where disk space is being used run

cd /
sudo du -h --max-depth=1 | sort -h

This command changes to the root directory and prints an ordered summary of the disk usage in human readable format. Note which directories use a lot of space, cd into one of them and run ls -l to see the files taking up space.

Update: Here’s a simpler command that creates a neat summary of each file and folder in the current directory:

du -cksh *

Get rid of packages that are no longer required

apt-get autoremove: removes libraries and packages that were installed automatically to satisfy the dependency needs of an application. If the application is removed those packages become useless. autoremove removes them and any old Linux kernels that were installed in a system upgrade.

sudo apt-get autoremove

Clear the apt cache

Ubuntu uses APT (Advanced Package Tool) for managing software packages. It keeps a cache of previously downloaded packages even after they are uninstalled. The cache can grow quite large over time.

The cache is kept in /var/cache/apt/archives. Check its usage by doing:

sudo du -h /var/cache/apt/archives

# Remove only the outdated packages
sudo apt-get autoclean

# Remove entire cache
sudo apt-get clean

Clear Systemd journals

Systemd keeps logs for many services on your computer and over time, these logs can take up significant amount of space. The commands below allow you to check how much space the logs take up and how to clear it.

# Check usage
journalctl --disk-usage

# Clear logs older than 3 days
sudo journalctl --vacuum-time=3d

Remove older versions of snaps

Snap stores at least two older versions of your application. Use the commands below to remove them

# Check disk space taken up by snaps
sudo du -h /var/lib/snapd/snaps | sort -h 

Run Bash script to remove unused snaps

You can use this script to clean all older versions of snaps from your computer. Save the script to a file, give it execute permission and run it:

#!/bin/bash
# Removes old revisions of snaps
# CLOSE ALL SNAPS BEFORE RUNNING THIS
set -eu
snap list --all | awk '/disabled/{print $1, $3}' |
    while read snapname revision; do
        snap remove "$snapname" --revision="$revision"
    done

Clear space used by docker objects

Docker objects accumulate over time and can eventually take up a lot of space. Consider running the docker prune command to reclaim space. I wrote an article on how to use it to free up space.

Conclusion

df, apt-get autoclean, autoremove and the docker prune commands are a good combination for reclaiming used space on your computer. I get the most space back from clearing docker images using the docker image prune command.