Menu Close

Compile and Replace Linux Kernel on Ubuntu

Here is a step-by-step guide to build and replace Linux kernel on Ubuntu.

While trying these steps for first time you should try these steps inside a virtual machine where you can access console.

1. Install Necessary Dependencies

To compile the Linux kernel, you need various tools and libraries:

sudo apt update
sudo apt install -y build-essential libncurses-dev bison flex libssl-dev libelf-dev

2. Download the Kernel Source Code

You can download the latest stable kernel source from kernel.org or use the following commands:

mkdir ~/kernel_build
cd ~/kernel_build
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.5.9.tar.xz # Example for kernel 6.5.9
tar -xvf linux-6.5.9.tar.xz
cd linux-6.5.9

3. Configure the Kernel

Use your current kernel configuration as a starting point:

cp /boot/config-$(uname -r) .config

Modify the configuration if needed using one of these tools:

  • Menu-based configuration:bashCopy codemake menuconfig
  • GUI-based configuration (if you have libgtk2.0-dev installed):bashCopy codemake xconfig

4. Compile the Kernel

  1. Clean the source tree to avoid conflicts:bashCopy codemake clean
  2. Compile the kernel and its modules. Adjust -jN to the number of cores in your CPU:bashCopy codemake -j$(nproc) make modules -j$(nproc) This step can take a while depending on your system’s capabilities.

5. Install Modules

Install the compiled modules to the appropriate directory in /lib/modules:

sudo make modules_install

6. Install the Kernel

Install the kernel and its associated files:

sudo make install

This will:

  • Copy the kernel image to /boot
  • Generate the initramfs
  • Update the GRUB bootloader

7. Update GRUB

If GRUB is not automatically updated, run:

vi /etc/default/grub

# set grub time menu so that it is easier to select kernel at boot time by "Advanced options for Ubuntu"
# you can choose the kernel that you build or build older kernel
GRUB_TIMEOUT_STYLE=menu
GRUB_TIMEOUT=10
sudo update-grub

8. Reboot Into the New Kernel

Reboot your system and select the new kernel from the GRUB menu (if it’s not set as default).

sudo reboot

9. Verify the New Kernel

After rebooting, check the running kernel version:

uname -r

10. Troubleshooting

If the new kernel fails to boot:

  • Reboot and select an older kernel from the GRUB menu.
  • Investigate /var/log/kern.log or /var/log/syslog for errors.

You can safely remove a faulty kernel by deleting its files from /boot and /lib/modules, followed by updating GRUB:

sudo rm /boot/vmlinuz-<faulty-version>
sudo rm -r /lib/modules/<faulty-version>
sudo update-grub