Check if the operating system already has a swap file
sudo swapon --show
The output shows the currently set up swap files. If there is no output, no swap file is in use.
To remove the swap file
# Disable the swap file usage
sudo swapoff </the swap file name>
# Delete the swap file
rm </the swap file name>
Allocate disk space for the new swap file in the root directory
cd /
sudo fallocate -l 8G /swapfile
Set up the permissions, so only the root user can access it
sudo chmod 600 /swapfile
Set up the swap file
sudo mkswap /swapfile
Enable the swap file
sudo swapon /swapfile
Make the swap file usage permanent, so it is used after every system boot. Add an entry into the /etc/fstab file. Open the file in the text editor
sudo nano /etc/fstab
Add the following line to the end of the /etc/fstab file, and save the file.
/swapfile none swap sw 0 0
Check the memory size including the swap file size
free -h
Check the disk size to make sure there is enough free disk space
df -h --total
Restart the computer and check the memory size again to make sure the swap file is in use again.
sudo reboot