When dealing with virtual machines in LXD or any other QEMU-based environments manually mounting a VM’s disk image can allow you to inspect its contents and retrieve data. This article walks you through the process of mounting a VM disk image for troubleshooting and data recovery.
1. Create a Mount Directory and Locate the VM Image
First, create a directory where you will mount the VM’s filesystem:
$ mkdir -p /root/Desktop/havm
Now, find to the directory where the VM disk image is stored. For those using LXD / Incus that’s typically under:
$ cd /var/lib/lxd/virtual-machines
In this directory, you’ll find a sub-directory for each VM and inside those a disk image named root.img
.
2. Calculate Partition Offsets
Now you know the image is at /var/lib/lxd/virtual-machines/havm/root.img
you may be tempted to mount it with mount-o loop root.img /root/Desktop/havm
, but that doesn’t work.
The problem is that the .img
files are not images of a partition, but of a whole disk – that means they start with the EFI partition. You have to find out the start of the OS partition and mount it with the offset
option of mount
. Use fdisk
to list the partition details:
$ fdisk -l /var/lib/lxd/virtual-machines/havm/root.img
Disk root.img: 32 GiB, 34359738368 bytes, 67108864 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 894818E3-EDC5-46A0-9E2D-1593EDC6BAD4
Device Start End Sectors Size Type
root.img1 2048 67583 65536 32M EFI System
root.img2 67584 116735 49152 24M Linux filesystem
root.img3 116736 641023 524288 256M Linux filesystem
root.img4 641024 690175 49152 24M Linux filesystem
root.img5 690176 1214463 524288 256M Linux filesystem
root.img6 1214464 1230847 16384 8M Linux filesystem
root.img7 1230848 1427455 196608 96M Linux filesystem
root.img8 1427456 67108830 65681375 31.3G Linux filesystem
The offset for mounting a partition is calculated using:
Offset = Start Sector * Sector Size
In my case the OS partition (root.img8
) starts at 1427456
and I’ve a sector size of 512
, so:
Offset = 1427456 * 512 = 730857472 bytes
3. Working With the Image
Now that we have the correct offset, we can mount the partition using the following:
$ mount -o loop,offset=730857472 /var/lib/lxd/virtual-machines/havm/root.img /root/Desktop/havm
After running this command, the filesystem should now be accessible at /root/Desktop/havm
. Use the Terminal or the GUI file explorer to retrieve the data you need.
After you have finished working with the mounted image, unmount it properly to avoid data corruption:
$ umount /root/Desktop/havm