Skip to content

How to Create a File System in a File and Mount It as a Loop Device

Updated 2 min read

Updated: 30 September 2026 · Applies to: util-linux losetup and mount on AlmaLinux and Rocky Linux 9 and 10, RHEL 9 and 10, Ubuntu 24.04 and 26.04, Debian 13

A file can hold a whole file system. Attached to a loop device, it behaves like a disk: you can format it, mount it and store files in it. This is handy for testing, for a fixed-size storage area, or for disk images. We ran the commands below on AlmaLinux 9.

1. Create the file

truncate -s 2G /srv/disk.img      # sparse file: uses disk space only as it fills
fallocate -l 2G /srv/disk.img     # or: reserve the full 2 GB now

fallocate is the better choice when the file system inside must never run out of space because the outer disk filled up.

2. Create a file system in it

mkfs.ext4 -q /srv/disk.img

mkfs works directly on the file; you do not need to attach a loop device first.

3. Mount it

mkdir -p /mnt/disk
mount -o loop /srv/disk.img /mnt/disk
df -h /mnt/disk
losetup -l                          # shows the loop device that mount attached

mount -o loop finds a free loop device and attaches the file automatically. To attach it yourself (for example to partition it), use losetup --find --show /srv/disk.img, which prints the device name such as /dev/loop0.

4. Mount it at boot

Add a line to /etc/fstab:

/srv/disk.img  /mnt/disk  ext4  loop,nofail  0 0

Test with umount /mnt/disk, systemctl daemon-reload and mount -a.

5. Detach it

umount /mnt/disk

A loop device attached by mount -o loop is released automatically on unmount. One you attached with losetup is released with losetup -d /dev/loop0.

Grow the image later

umount /mnt/disk
truncate -s 4G /srv/disk.img
e2fsck -f /srv/disk.img && resize2fs /srv/disk.img
mount -o loop /srv/disk.img /mnt/disk

There is no fixed limit on the number of loop devices on current kernels; see loop devices on current Linux kernels.

Official documentation: losetup manual and mount manual (loop devices).

Related services

KVM VPS hosting

NVMe SSD and full root access, with Free Basic Managed Support.

Unmanaged dedicated servers

full root access and free IPMI KVM, with Free Basic Managed Support.

Linux server management

hardening, patching, monitoring and automation for Ubuntu, Debian, RHEL and AlmaLinux.

Was this answer helpful?

Still stuck? Open a ticket