Many Linux distributions do not clean up old kernels when new ones are installed and after years of updating your server, you’ve likely accumulated lots of different kernel versions. When upgrading within the same OS version, old kernels don’t typically get cleaned up automatically. This is to enable you to safely “rollback” to an older kernel version if you experience problems with a newer one.
A common problem of this is the /boot partition filling up with old kernel images, and you can safely uninstall any kernel version that you are not currently running.
And another reason is to clean up the Grub boot menu. In Ubuntu, Grub boot menu is hidden by default, and to display it you have to press “SHIFT” at boot time.
To identify your current running kernel, use:
uname -r
This will output something like:
5.1.16-300.fc30.x86_64
And to list all installed kernels:
rpm -qa |grep kernel
You can remove the kernel and kernel-devel packages for any kernel that you are not currently running. In this example, you’ll not want to remove kernel-5.1.16-300.fc30.x86_64. You will usually not find more than one instance of kernel-headers or kernel-firmware, but if you do, you can remove the unused version of those too.
Note: If you’re running Ksplice for kernel updates, there are actually two kernels you should not remove: that’s the one listed above, as well as the one shown in the output of:
uptrack-uname -r
While Ksplice patches the kernel in memory, removing an existing RPM for the acting kernel can cause unpredictable behavior.
Remove the old kernels as so:
rpm -e kernel-2.6.32-358.0.1.el6.x86_64
rpm -e kernel-devel-2.6.32-358.18.1.el6.x86_64
And so on. Doing this will free up the unneeded files from /boot partition, however, disk space is not a problem in modern systems.
Ubuntu
More suptile way to remove old kernels in Ubuntu is to use byobu:
sudo apt-get install byobu
and run it periodically:
sudo purge-old-kernels --keep 3
After removing old kernels, new grub boot menu will be available in next reboot.
To update Grub you need to run:
update-grub2
and reboot afterwards:
systemtcl reboot
BONUS: Kernel clean-up script
apt purge $(dpkg --list linux-{headers,image,modules}-\* \
| awk '{ if ($1=="ii") print $2}' \
| egrep '[4-9]\.[0-9]+\.[0-9]+-[0-9]+' \
| egrep -v $(uname -r | cut -d"-" -f1,2))
apt autoremove
update-gru
Thanks to Ivan Markov for this script! 🙂
Debian
List all kernels:
dpkg --list | grep linux-image
Remove old kernels by name:
apt-get --purge remove linux-image-XXX
CentOS
Install the yum-utils package:
yum install yum-utils
run the following command to remove old kernels:
package-cleanup --oldkernels --count=32
The count parameter defines how many kernels you want to keep. So in the above example, the last three kernels will be retained. You do not have to run this command every time you update the kernel version though, because there’s a parameter you can add to /etc/yum.conf to do this automatically:
installonly_limit=2