SSDNodes hosted AlmaLinux doesn’t have a swap file by default (if you don’t have a VPS yet, but you’re thinking about getting one, have a look at this article on installing a VPS. Some times you may find your RAM becoming low and you want to free some up. By adding a swap file to Linux, you can offload some unused RAM for retrieval later. Here I’ll show how to add a swap file to allow this to occur.
Check if you already have a swap file
It’s prudent to check if you already have a swap file. If you’re doing this on another distro, it may already have one. Type the following to check
swapon --show
If nothing comes back, then you don’t currently have a swap file, so let’s proceed.
Create a swap file
Type the following to create a swap file. In this example we’ll create a 4GB swap file
fallocate -l 4G /swapfile
This will create a 4GB swapfile in the /swapfile directory. It’s not quite ready for use yet. We need to set the correct permissions with
chmod 600 /swapfile
and we need to format the swap file
mkswap /swapfile
Enabling the swap file
We now need to enable the swap file with the following command
swapon /swapfile
and confirm its active with
swapon --show
free -h
The swapon should show the mounted swap file and the free should confirm it’s size.
Make the swap file permanent
To make the swap file permanent, we need to add it to the /etc/fstab file. We can do this as follows
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
this will add the line ‘/swapfile none swap sw 0 0’ to /etc/fstab so that when the server reboots it will reapply the swap file.
That’s it. You now have now added a swap file to Linux and enabled it.