Making a KVM-bootable image

I’ve lost count of how many times I’ve had to re-learn how to create a bootable image from a filesystem tree (such as a tarball of a root filesystem, or a Xen partition image).  If for no other reason than recording it for next time, here it is.

Create an image file (lets assume 4MB will do it), partition it, mount the partition, and copy in the root filesystem

% dd if=/dev/zero of=test.img bs=1M count=4
% parted test.img mklabel msdos
% parted test.img mkpart primary 0 4
% losetup /dev/loop0 test.img
% kpartx -a /dev/loop0
% mount /dev/mapper/loop0p1 /mnt
% cp -rav /path/to/root /mnt/

Now, you need to put a kernel and an initrd on it.  Assuming a RedHat-like system:

% mkdir -p /mnt/boot/grub
% cp /boot/vmlinuz-`uname -r` /mnt/boot/vmlinuz
% mkinitrd –with ata_piix –with rtl8139 /mnt/boot/initrd `uname -r`

Next, you need a bootloader:

% cat >/mnt/boot/grub/grub.conf <<EOF
default 0
timeout 5
title My System
kernel /boot/vmlinuz root=/dev/sda1
initrd /boot/initrd
% cat >/tmp/grub_setup <<EOF
device (hd0) /path/to/image       # NB: Put your full path here
root (hd0,0)
setup (hd0)
% grub < /tmp/grub_setup

That’s it!  Now you can unmount your image:

% umount /mnt
% kpartx -d /dev/loop0
% losetup -d /dev/loop0

The resulting image should boot normally in QEMU, KVM, etc.

Category(s): Codemonkeying, Linux
Tags: ,

Comments are closed.