Creating virtual disks using dd and losetup.

To create an image file, in this case a “virtual disk”, use “dd” command. The below command will write zeros to a file of a specified size.

dd if=/dev/zero of=1GB_disk.img bs=1M count=1024

Once completed, a partition can be created using cfdisk or fdisk command. Then the filesystem should be created using mkfs.ext4

cfdisk 1GB_disk.img

Now, you can proceed to setup a loop device for you image. This requires the use of “losetup”. This command will assign an available loop device (-f option to find one) to the partition on the image, and show the name a loop device (–show option):‚Äč

losetup -Pf --show 1GB_disk.img

If successful, you should be able to access the partition by mounting the image.

[root@s1 disk]# lsblk|grep loop
loop0 7:0 0 1G 0 loop /mnt/disk
[root@s1 disk]#

mount /dev/loop0 /mnt/disk

[root@s1 disk]# df -hP /mnt/disk/
Filesystem Size Used Avail Use% Mounted on
/dev/loop0 976M 46M 863M 6% /mnt/disk
[root@s1 disk]#

To remove a loop device just run:

losetup -d /dev/loop0