Linux – Use losetup and dd to make filesystems images ready to be deployed

dddisk-imagehard drivelinuxpartitioning

Introduction

Using dd, one can easily backup the MBR and partition table of a disk. It's as easy as: dd if=/dev/disk2 of=~/Desktop/disk2_mbr bs=512 count=1

One can also backup whole partitions: dd if=/dev/disk2s1 of=~/Desktop/disk2_partition1

The other way around works too: with dd if=~/Desktop/disk2_mbr of=/dev/disk3, one can replace another disk MBR and partition table (beware, data loss on disk3).

Then, to restore the first partition, one does: dd if=~/Desktop/disk2_partition1 of=/dev/disk3s1

(The point of dding separately the MBR and the partition is that you don't need to dd the whole disk; if your partition is small it will be much faster.)

Fine, all this dd magic works great for me. It makes it so easy to backup and restore from whatever system whatever hard drive.

Loop devices

Virtual system image creation works great too.

To create a new, empty media-image (30 GB), one can do: dd if=/dev/zero of=/my-media-image bs=1k count=30240000

Then, to assign the media to a loopback device: losetup /dev/loop0 /my-media-image

To create a filesystem on the media-image, one does: sudo mkfs -t ext3 -L MYVIRTUALFS -M /media/MYVIRTUALFS -I 128 -m 0 -b 4096 -O sparse_super -T largefile4 /dev/loop0

The media can then be mounted: sudo mkdir /media/MYVIRTUALFS && mount /dev/loop0 /media/MYVIRTUALFS

Problem

What I don't understand is that, if I unmount the disk (sudo umount /media/MYVIRTUALFS), then delete the loopback device (sudo losetup -d /dev/loop0), I would have thought that the original media (/my-media-image) would be the exact same thing as a dd clone of /dev/loop0

Apparently it's not, because if I do dd if=/my-media-image of=/dev/disk4 (beware, data loss on disk4), disk4 is corrupted, and unmountable.

Why?

It makes it possible to create a virtual filesystem from a Linux macine, complete with partition table, data, etc… then just copy the media-image (/my-media-image in my example) to another system (Macintosh in my case), where it's ready to deploy to real hard drives. It should even work on Windows, which has GUIs for dd.

What am I missing?

Best Answer

As killermist mentioned, the error was that I had forgotten to create partitions before creating a filesystem. The instructions in the question are correct and create perfectly valid disk images, all one has to do is to create partitions, just after mounting the loop device, and just before creating a filesystem on it.
So the correct sequence is
losetup....
parted --script /dev/loop0 mktable msdos mkpart primary 2048s 100%
sudo mkfs...

Related Question