Mount KVM or Xen disk image in Linux

If you have a single partition virtual disk, you can mount the image file directly.
It is a bit more work if you have multiple partitions on the virtual image, as you cannot mount these partition directly. We here have two ways to mount it.

Way One: Create device maps from partition tables

This can be done by kpartx. Kpartx is derived from util-linux‘s partx, reads partition tables on specified device and create device maps over partitions segments detected. It is called from hotplug upon device maps creation and deletion.

[joseph@admon images]$ sudo kpartx -v -a imagename.img
add map loop0p1 : 0 7766802 linear /dev/loop0 63
add map loop0p2 : 0 224910 linear /dev/loop0 7766865

This creates mappings for the device that can be accessed easily. For example, you can mount it,

[root@hostname /]# mount -o ro /dev/mapper/loop0p1 /mnt

Or run fsck directly over that partition.
To clean up device mappings, (after unmounting any mounted partitions):

[joseph@admon /]$ sudo kpartx -d /dev/loop0


Way Two: Use mount with offset

With specific offset to mount, we can mount a given partition as well. The offset can be calculated from the output of fdisk.  Here is an exmaple,

mount with offset
The start sector is 32, and block size 512 bytes, so the offset is 32*512, which is 16384. Then we can mount the partition like this,

mount -o offset=16384 ./Test.img /mnt

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.