1 min read

Linux: Virtual Block Devices

How hard is it to make a virtual block device? Turns out, easy.

I was reading Fly.io post Making Machines Move and I was wondering how hard it is to create a virtual block device. Turns out, not too bad at all.

  1. Create an image
dd if=/dev/zero of=/path/to/virtual-disk.img bs=1M count=1024
  1. Setup a loop device
losetup /dev/loop0 /path/to/virtual-disk.img
💡
losetup is really saying "loop setup".

A loop device (or loopback device) is a pseudo-device in Unix-like operating systems (aka Linux) that allows a file to be accessed as if it were a block device.

Here are some common use cases (thanks ChatGPT):

- Mounting Disk Images: A common use is to mount ISO files, filesystem images, or other disk images without needing to burn them to physical media.

- Testing Filesystems: Developers can create a filesystem within a file and mount it to test its behavior without using a physical disk.

- Creating Virtual Storage: Useful in virtual environments to provide storage for virtual machines or containers.

(☝️ we're using it for the 3rd point)
  1. Confirm the loop device exists with:
losetup -a
  1. Create a Filesystem on the device
mkfs.ext4 /dev/loop0
👋
loop0 is coming from the output of losetup -a and depending on your setup your device might be loop1, etc.. Make sure to check!
💡
mkfs: "make filesystem." usually paired with a filesystem type like ext4. Without a filesystem, the operating system won't be able to manage files with the loop device.
  1. Mount the device
mkdir /mnt/myblockdevice
mount /dev/loop0 /mnt/myblockdevice
  1. Confirm the drive is mounted with the df command
  2. Unmount when you're done
umount /mnt/myblockdevice
losetup -d /dev/loop0

(you can delete the image at this point too if you want)


Bonus: Encrypted block device

Mostly the same as above with a few extra steps:

# Create a file for the loop device
dd if=/dev/zero of=/path/to/encrypted.img bs=1M count=1024

# Set up a loop device
losetup /dev/loop0 /path/to/encrypted.img

# Encrypt the loop device
cryptsetup luksFormat /dev/loop0

# Open the encrypted loop device
cryptsetup luksOpen /dev/loop0 encrypted

# Create a filesystem on the encrypted device
mkfs.ext4 /dev/mapper/encrypted

# Mount the encrypted filesystem
mount /dev/mapper/encrypted /mnt/encrypted

The next step is to explore the device mapper framework and see what it takes to manage logical volumes.