Linux – Booting linux system from chroot: is there a better way to do this

bootchrootdebianlinux

I want to set up Grub menu entry to boot into chrooted system (installed chrooted debootstrap to avoid touching existing system too much).

Currently I do the following to attain it:

  1. Install linux-image and friends inside chrooted environment

  2. Manually remaster initramfs to chroot into the system instead of usual behaviour:

rootmnt=$rootmnt/root/squeeze
...
#exec run-init ${rootmnt} ${init} "$@" <${rootmnt}/dev/console >${rootmnt}/dev/console
exec chroot ${rootmnt} ${init} "$@"  <${rootmnt}/dev/console >${rootmnt}/dev/console

3.. Add entry to /boot/grub.cfg:

menuentry 'Chrooted debian Squeeze' {
    ...
    linux   /root/squeeze/boot/vmlinuz root=... rw
    initrd  /root/squeeze/boot/initrd-chroot
}

It works but not easy to set up and needs manual hacking every time initrd should be changed. How to do it better?

Best Answer

I came across the same issue and ended up writing this to make it work painlessly across different systems (debian, ubuntu currently):

Run make_chroot_initrd script to create a new chroot-enabled initrd image from the existing one:

#  ./make_chroot_initrd /chroot/trusty/boot/initrd.img-3.13.0-32-generic
making new initrd: /chroot/trusty/boot/initrd.img-3.13.0-32-generic.chroot

The new image will be exactly the same, except now it can handle a chroot= boot parameter.

With grub2 as bootloader you can add an entry to /boot/grub/grub.cfg:
(or perhaps better /etc/grub.d/40_custom)

menuentry "ubuntu trusty, (linux 3.13.0-32) (chroot)" {
    insmod ext2                       # or whatever you're using ...
    set root='(hd0,7)'                # partition containing the chroot
    set chroot='/chroot/trusty'       # chroot path
    linux   $chroot/boot/vmlinuz-3.13.0-32-generic root=/dev/sda7 chroot=$chroot rw
    initrd  $chroot/boot/initrd.img-3.13.0-32-generic.chroot
}

(change files/partitions to match yours)

System-wide install

Once you're happy with it you can make the changes permanent
(until initramfs-tools package gets upgraded).
In the chrooted system:

# cd /usr/share/initramfs-tools
# cp -pdrv .  ../initramfs-tools.orig       # backup
# patch -p1 < path_to/boot_chroot/initrd.patch
# rm *.orig */*.orig
# update-initramfs -u

From now on regular initrd image will support chroot booting.
No need to use a separate initrd.chroot which may get out of sync with it then.

See boot_chroot for details.

Related Question