Remove Old Kernels on CentOS Linux and other distros

After a few years and many yum updates later, the hard drive begins to fill up. There may be many versions of the Linux kernel. Many of which may be removed and to do this the yum-utils package is needed.

Pre-CentOS 8

Install the yum-utils package.

yum install -y yum-utils

Check your running version.

[root@server01 opt]# uname -a
Linux server01 2.6.32-504.8.1.el6.x86_64 #1 SMP Wed Jan 28 21:11:36 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

Check for installed kernels.

rpm -q kernel

The result may look something like this.

[root@server01 opt]# rpm -q kernel
Note that the running kernel is older than the latest kernel that has been downloaded.  Before cleaning up your kernels you may want to reboot to the new kernel to see if everything is still working as expected before cleaning out the older kernels.

Remove the old kernels, except two.  Keep the current one and at least the one more to fall back to if the current should fail you.

package-cleanup --oldkernels --count=2

Follow the instructions and you can reverify the number of kernels with the command above.

To make this permanent, update the /etc/yum.conf and change the installonly_lime value to 2.


CentOS 8

The package-cleanup functionality to remove the old kernels was removed; however, this command works well.

dnf remove --oldinstallonly --setopt installonly_limit=2 kernel

Against my better judgement, I wanted to clean out all the kernels to remove any remnant that existed in the grub menu. Using the steps above to determine the running kernel, I removed any other kernel and reinstalled the running kernel.

rpm -qa kernel
uname -r
yum remove kernel*-4.18.0-240.22.1.el8_3.x86_64
yum reinstall kernel*

Straying even further past good judgement, I wanted to rebuild the rescue image to match the running kernel.  This worked!

rm /boot/*rescue*
dnf reinstall kernel-core
-rw-r--r--. 1 root root 189464 Apr 12 01:35 config-4.18.0-240.22.1.el8.x86_64
drwxr-xr-x. 3 root root 4096 Mar 5 2020 efi
drwx------. 4 root root 4096 Jun 4 15:12 grub2
-rw-------. 1 root root 73873402 Jun 4 15:26 initramfs-0-rescue-e134bbfaabf5466c8da8d620a3b49d20.img
-rw-------. 1 root root 28243700 Jun 4 15:25 initramfs-4.18.0-240.22.1.el8.x86_64.img
drwxr-xr-x. 3 root root 4096 Mar 5 2020 loader
-rw-------. 1 root root 4034919 Apr 12 01:35
-rwxr-xr-x. 1 root root 9486176 Jun 4 15:25 vmlinuz-0-rescue-e134bbfaabf5466c8da8d620a3b49d20
-rwxr-xr-x. 1 root root 9486176 Apr 12 01:35 vmlinuz-4.18.0-240.22.1.el8.x86_64