Skip to content

Swap on a file

Using a file based swap has several benefits. Among the most important for me are the fact that it can be increased and decreased extremely easily; the other bonus, just as important is that I don't need to maintain complex partition tables.
The above reasons are especially important if you are running a virtualised OS where extra flexibility/simplicity helps and the performance difference is not really that big[1], both swap types are SLOW. :-)

Let's proceed. First we need to create a - say - 500M file; the best way to do it is via "fallocate" as it requires virtually no I/O (man fallocate), but you can also use good old "dd" if you're on an old OS:
fallocate -l 500M /swap.IMG

Next we need to format it, add it to fstab and mount it:
chmod 0700 /swap.IMG
mkswap /swap.IMG
echo "/swap.IMG		swap		swap	defaults	0 0" >> /etc/fstab
swapon -a

If you ever get in a situation where you need to increse swap you can simply do the above for a new file or just increase the current file:
swapoff /swap.IMG
fallocate -l 1000M /swap.IMG
mkswap /swap.IMG
swapon /swap.IMG
VoilĂ !

If you're working on a virtual machine you might want to avoid swapping as much as possible (many swapping instances generate significant I/O). This can be done via sysctl:
sysctl -w vm.swappiness=0
And also add "vm.swappiness = 0" to /etc/sysctl.conf to make it permanent between reboots.
"vm.swappiness = 0" means it will swap only to avoid an out of memory condition.

HTH.

[1] - http://lkml.org/lkml/2005/7/7/326