
Milo G. answered 05/29/22
User since 6th grade; managing Linux servers since 9th grade
Dear Sammy,
Assuming you're on an ext-related filesystem, the process looks something like this:
- Use "sudo swapon --show" to make sure there's not already an active swap. No output = no swap.
- You have two good options for correctly allocating the bytes for the swapfile: fallocate (faster, ext3 only) and dd (slower, works everywhere).
- For fallocate: "sudo fallocate --length 1G /swapfile". "1G" here indicates 1 gigabyte.
- For dd: "sudo dd if=/dev/zero of=/swapfile bs=1K count=1M
- We choose the numbers "1K" (1 kilobyte, or 1,024 bytes) and "1M" (1 megabyte, or 1,048,576 bytes) because multiplying the two together will yield 1 gigabyte of space allocated for the swapfile (1,024 * 1,048,576 = 1 gigabyte).
- Restrict permissions on the swapfile by executing "sudo chmod 600 /swapfile".
- The number "600" conveys to the system that the user (since we use "sudo", this is the root user) should be able to read and write the swapfile, and that nobody else should be able to do anything (read, write, or execute) to the file in question.
- Convert the empty file into the swapfile running "sudo mkswap /swapfile".
- If you get an error message mentioning holes, and you created your swapfile with the "fallocate" command, you're probably running an ext4 filesystem; try again using dd.
- Alert the system to the swapfile non-persistently by running "sudo swapon /swapfile". This will not persist beyond the next reboot, but does let us test the swapfile to make sure it works before making it persistent. Run "sudo swapon --show" to make sure the command did as asked (output = success).
- At the bottom of the /etc/fstab file, add "/swapfile none swap sw 0 0".
- The first option is our swapfile, the second option tells our system that the swap shouldn't be "mounted" (i.e., interpreted as a filesystem akin to an external hard drive or flash drive and given its own folder on your system), the third option tells the system to treat the swapfile as the swap, the fourth option instructs the system to run the "swapon" command on the swapfile, and the last two options only apply to storage devices and not to your swap.
Reboot, and run "sudo swapon --show" again. If the command shows output, we have succeeded in creating a persistent swapfile. Otherwise, you may have missed an error message in one of the previous steps - let me know if you have trouble with anything here (including understanding why we're doing any of this in the first place!).