Linux: Where to put the swap file

Solution 1:

AFAIK there is no location defined in the File System Hierarchy Standard.

Because /var is for often-changed files, I would say it is okay to place it here. But remember that if you use a flat-file swap instead of a partition, consider to use a fast file system for /var.

Solution 2:

The conventional way is to have a partition dedicated to swap. If you use a file it's at your own discretion, but Malte's suggestion of the file system being important is a good one.

Solution 3:

Just to add my 2 cents to Malte's and Caleb's answers, and also to the excelent reference by Paul:

Using swap partitions instead of swapfiles was mentioned often. You have to see that the main issue with swapfiles is not performance (the kernel takes care of that), but instead needing contagious non-sparse disk space. Therefore it is best to create all swapfiles right after the creation of the underlying filesystem. Once the filesystem is in use, with file fragments scattered all around, it will be hard to get hold of some contiguous space. Still, in contrast a partition does not offer anything better: it is guaranteed to be a continuous space, but you also have to create it early on, and it is a major pain to change later.

Also, to address the main question of where to put the swapfile. Just like with swap partitions, the contents of a swapfile is highly confidential in nature, therefore using encryption is recommended. As in case of whole partitions where mostly LVM volumes over LUKS is the practice, swapfiles should be placed on a filesystem which is on top of a LUKS encrypted device. You have to keep in mind, that there are various problems with hibernation on encrypted swap. Also, don't forget access rights. Just like you don't want someone to read or write to your memory, protecting swapfiles is essential. Possibly the best place is inside a directory access-able only by root. (e.g. /var/swap/swapfile01_8G)

As mentioned before creating swapfiles after the system is in use might be a problem. Therefore using this for scaling up after finding out later that more swap is needed could be unfeasible. On the other hand scaling back while having the total swap space made up of multiple swapfiles would be easy. For this reason, it might worth allocating swap space more judiciously, and in multiple files, because it will be easy to scale back if you confirm later that it is significantly oversized. (Buy more disk space for god's sake)