What Is a Swap File?
When the system’s memory is low, a swap file is a system file that generates temporary storage space on a solid-state drive or hard disk. The file frees up memory for other programs by swapping a portion of RAM storage from an inactive program. Let’s create a swap file On Ubuntu 22.04 LTS.
Update and upgrade
Before creating a swap file, run the following command.
sudo apt update && sudo apt upgrade -y
Check Swap Status
Verify whether a swap space is already available on your server. Virtual machines rarely come with a swap space activated by default. Use the following command to examine the swap space.
sudo swapon --show
Check Drive Capacity
Before creating a swap file first, check the current disk usage to make sure that you have enough space.
df -h
Allocate Swap File Space on Drive
At this point, you can add 1 GB of space by making a swap file. You can also increase the amount of space. To increase the swap file space change (1G) to as you need.
sudo fallocate -l 1G /swapfile
Change Permissions of Swap File
You now have a swap file that is the proper size and can be used as swap space. Set up the proper permissions and then continue.
sudo chmod 600 /swapfile
Check Swap File Size and Permissions
Now Verify the changed permissions and then continue.
ls -lh /swapfile
Make Swap File
Run the following command to create the swap file.
sudo mkswap /swapfile
Enable Swap
Let’s enable the swap file.
sudo swapon /swapfile
Open fstab for Editing
Make the swap file available even after rebooting the server. In order to do that we need to configure the fstab.
sudo nano /etc/fstab
If some reason above command did not work it means you have to install the nano software. To install nano run the following command. Then try the above command again.
sudo apt-get -y install nano
Add this line in fstab
/swapfile none swap defaults 0 0
Check Swap Parameters
To check the current value of swappiness run the following commands one by one.
cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure
Change Swap Parameters
Let’s change the values of swappiness by running the below commands.
sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50
Open sysctl.conf for Editing
To make the above changes permanent we need to configure the sysctl.conf file.
sudo nano /etc/sysctl.conf
Configure sysctl.conf
Add these lines end of the document (/etc/sysctl.conf)
vm.swappiness=10
vm.vfs_cache_pressure=50
Check Swap File
Let’s check the swap file status.
sudo swapon --show
Reboot the server
After completing all the actions reboot your server or instances.
You must be the root user in order to restart the server. Observe the instruction below.
Sudo su
reboot
Conclusion
You now understand how to create a swap file On Ubuntu, turn on the swap space, and customize it.
If you want Debian swap file Click to read the article.