If you have a case of having file system as btrfs, you will know that you can't have swap files on such systems. In such case, you probably need a partition. If you're running your server on AWS EC2, then you can even opt for having SSD as your swap partition, especially if your other EBS if on HDD.
You will have to create a new volume in your AWS console or via AWS API.
Once you have created your volume, you must attach it to your instance.
You can find your newly attached volume with:
You should see a disk called xvdf, or another letter, that has 8G of space. In this tutorial, I'm assuming your disk is xvdf.
In this tutorial, I'm assuming you have no swap.
You can check for existing swap with:
sudo swapon --show
If there is no output, that means you have no swap space currently.
You can verify no existing swap with:
If you see that swap has 0B, that means there is no active swap present in system.
Format your partition with:
sudo mkswap /dev/xvdf
You should see something like:
Setting up swapspace version 1, size = 8 GiB (8589930496 bytes)
no label, UUID=d3a23c79-5144-47fa-b422-885ebf63e2fc
Take note of your UUID. You will need it.
You need to configure your fstab with the new swap partition.
echo 'UUID=d3a23c79-5144-47fa-b422-885ebf63e2fc none swap sw 0 0' | sudo tee -a /etc/fstab
Be sure to replace your UUID in this command.
Reboot your computer for swap to take effect.
Run these commands to see that you have 8G for swap space.
sudo swapon --show
If you don't see your new swap space, something has gone wrong somewhere as you were following this tutorial.
Swappiness is a parameter for the system to determine how often your system swaps data out of RAM to swap space. The values are represented from 0 to 100, in percentages. By default, the value is 60.
You must remember that a swap on HDD is time costly, while a swap in SSD is lifespan costly. Since I'm running a server, I would prefer a value closer to 0, only to use RAM when absolutely neccessary. In some use cases, using swap actually increases performance.
Choose your ideal percentage, then run the following:
sudo sysctl vm.swappiness=10
I chose 10 so that it will use swap sparingly.
To make this value permanent during reboots, open /etc/sysctl.conf:
sudo nano /etc/sysctl.conf
Then add the following at the bottom:
Having swap has many advantages. In some cases, it will safe a technician from certain doom due to application crashes.
For me, I managed to lower my operating cost of running instances in AWS. After all, if I don't mind a bit of performace hit from running swap in SSD. In return, I get to half the cost of the instance running cost.
If you're looking to have a swap file instead of a swap partition, check out my other tutorial.