I know how to create and use a swap partition but can I also use a file instead?
How can I create a swap file on a Linux system?
Let it be clear, that there is a little overhead when dealing with a file instead of a partition.
Further, I myself have on several machines a swap file on
mdadm RAID, therefore there's yet another overhead. But if you adjust
vm.swappiness wisely to a more acceptable value than 60, which is the default, you should have no problem.
For instance, I have 32GB RAM server with 32GB swap file on RAID6 with
vm.swappiness = 1. Quoting the Wikipedia:
vm.swappiness= 1: Kernel version 3.5 and over, as well as Red Hat kernel version 2.6.32-303 and over: Minimum amount of swapping without disabling it entirely.
In this example, we create a swap file:
8GB in size
Change these two things accordingly to your needs.
Allocate space for the swap file:
dd if=/dev/zero of=/raid1/swapfile bs=1G count=8
Optionally, if your system supports it, you may add
status=progress to that command line.
Note, that the size specified here in
G is in GiB (multiples of 1024).
Change permissions of the swap file, so that only
root can access it:
chmod 600 /raid1/swapfile
Make this file a swap file:
Enable the swap file:
Verify, whether the swap file is in use:
Open a text editor you are skilled in with this file, e.g.
nano if unsure:
To make this swap file available after reboot, add the following line:
/raid1/swapfile none swap sw 0 0