When you are building a database or configuring a virtual machine swap file, you cannot use sparse files (like those created by the truncate command). Sparse files are “fake”—they report a large size, but they do not actually reserve any physical sectors on the hard drive. If you need a massive 10GB file that physically locks down and guarantees 10GB of contiguous sectors on the SSD (so no other program can overwrite them), you must preallocate the space using the fallocate command.
Why fallocate is Faster Than dd
Historically, system administrators used the dd command (e.g., dd if=/dev/zero of=swapfile bs=1M count=10000) to generate massive files. This command works by literally writing the number zero, sector by sector, ten billion times. Writing 10GB of zeroes takes several minutes on an HDD and causes significant, unnecessary write-wear on an SSD’s flash memory cells.
The fallocate utility bypasses this. Instead of writing zeroes, it talks directly to the filesystem architecture (such as ext4 or XFS). It instructs the filesystem to permanently reserve a contiguous block of physical sectors and assign them exclusively to your new file. Because it only updates the filesystem’s allocation tables and writes zero actual data payload, it can reserve a 100GB file in less than a single second.
How to Preallocate a Massive File
To reserve physical disk space, use the -l (length) flag followed by your required capacity.
To instantly allocate a massive, contiguous 50-Gigabyte file, open your terminal and run:
fallocate -l 50G massive_database_container.img
You can verify that the space has actually been physically subtracted from your hard drive’s available capacity by running the df -h command before and after you execute the allocation.
Advanced Usage: Punching Holes in Files
The fallocate command can also perform the reverse operation: freeing up disk space without deleting the file. If you have a massive 50GB virtual machine disk image, but you know that gigabytes 10 through 15 are currently empty inside the VM, you can instruct fallocate to “punch a hole” in the file.
Using the --punch-hole flag alongside the offset and length parameters, the command tells the filesystem to instantly release those specific physical sectors back to the operating system, while leaving the rest of the file perfectly intact. This advanced technique allows storage administrators to reclaim massive amounts of wasted disk space from database containers without causing any downtime.