Creating a swap file for swapping
July 9th 2020 on Dušan's blog
If you're totally new to the concept of swapping on GNU/Linux I highly advise you to check out this article. This procedure has the potential to break your system entirely if done incorrectly. You have been warned.
As the article puts, swapping is essentially a process by which a chunk of memory (page) is copied onto the disk to free up a portion of system memory.
Traditionally, swapping has been done by creating a partition on the disk, called a swap partition, and leveraging that disk space for swapping. However in situations where disk space comes at a premium, this is less than ideal, a swap file is more convenient. A swap file can be extended/reduced or removed altogether more easily.
As a rule of thumb you should create a swap file that is the same size or double to that of system memory. However I personally don't consider swap space essential on devices that exceed 16GB of RAM.
We can use the dd command to create a file on the disk the size of our choosing. Be careful when using dd though, as if used incorrectly it has the potential to overwrite unwanted parts of the disk (hence the nickname "disk destroyer").
To create a 2GB file for swapping we can run this command:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
This will write 2048 blocks, 1MB each giving us a total of 2GB.
We need to make sure that only the owner (in this case root) has access to the file. We can do that by setting the mode of the file to 600.
sudo chmod 600 /swapfile
Then after setting the correct permissions we need to format the space contained in that file for swapping.
sudo mkswap /swapfile
Finally to enable swapping we can turn it on using this command:
sudo swapon /swapfile
As a final step, to make the swap space be automatically mounted by the system across system reboots we need to edit the fstab file. Add the following line as the last line to your /etc/fstab file using your preferred text editor and reboot. Be careful not to modify anything else or your system may fail to boot.
/swapfile none swap defaults 0 0