How to clean your Ubuntu instance clean

Not every server is a docker provisioned fully CI/CD workflow. Sometimes you want to spin up something small for a side project or blog. Sometimes it's a dev server in the office or a small cloud instance for a thing you are doing. It might require some manual cleanup.


Keep the APT cache clean

Ubuntu keeps every update it downloads on disk in case you need it again. This command shows how big the cache is.

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


# 690M     /var/cache/apt/archives

Run sudo apt-get clean to clean the cache.


Remove old kernels safely

You can quickly see which kernel is the current one by running,

uname -r

# Outputs
4.13.0-1002-gcp

And a list of all kernels by running,

sudo dpkg --list 'linux-image*'|awk '{ if ($1=="ii") print $2}'|grep -v `uname -r`

# Outputs
linux-image-4.13.0-1006-gcp #current
linux-image-gcp

That means you can run commands to safely delete kernels that are not used anymore.

sudo apt-get autoremove --purge

As a bonus, this will remove the unused kernels and also the packages that are outdated.


Clean out /tmp

The /tmp folder fills up space but often overlooked when cleaning up. This will clean up files/folders older than 10 days.

sudo find /tmp -type f -atime +10 -delete

Rotate log files

A neat linux utility exists called logrotate. This tool rotates the logfiles usually contained in /var/log and saves it with an incremental number and archives files older than a day for you to use however you want.

ll /var/log

# Outputs
Jan 10 07:22 syslog
Jan 10 06:25 syslog.1
Jan  9 06:25 syslog.2.gz
Jan  8 06:25 syslog.3.gz

Delete all archived log files older than a week

To find all archived rotated logs older than 5 days run,

sudo find /var/log/**/*.gz -depth -print -type f -atime +5

# Outputs
/var/log/nginx/access.log.2.gz
/var/log/nginx/access.log.3.gz
/var/log/nginx/access.log.4.gz
/var/log/nginx/access.log.5.gz
/var/log/nginx/access.log.6.gz
/var/log/nginx/access.log.7.gz

You can safely delete those by replacing the -depth -print part with -delete

sudo find /var/log/**/*.gz -delete -type f -atime +5

If you know of any good ones I have missed, Please get in touch and I will add it :D

Show Comments

Get the latest posts delivered right to your inbox.