What is Swap memory?
Swap is the space partitioned from disk used to store temporary system files, in that case where RAM utilization is high and the system manages to move less active files to swap memory.
Step 1 – Checking the system for any existing swap
Before proceeding, check if the system is already using swap space or not. We can keep multiple swaps, but generally, we use one.
Use the below command to check the existing swap:
sudo swapon --show
If you get back with any output, this means your system does already have swap space available.
You can verify that there is an active swap using the below command:
Step 2 – Check available space on the Hard Drive
Check disk usage before creating a new swap file, Use this command:
The volume with/in the Mounted on the column is the volume in this case. Generally, an amount equal to or double the amount of RAM on your system is good to go.
Step 3 – Creating a Swap File
We can create a swap file with the help of the fallocate program.
Since the server in our example has 4G of RAM, we will create a 4G file in this guide. Modify the swap size according to your requirement :
sudo fallocate -l 4G /swapfile
Step 4 – Enabling the Swap
First, remove extra permissions of the file created for a swap so that only the users with root privileges can read the contents.
sudo chmod 600 /swapfile
We can now mark the file as swap space by using the command below:
sudo mkswap /swapfile
Setting up swapspace version 1, size = 4096 MiB (4294967296 bytes)
no label, UUID=7e895807-2ba9-550f-agd6-576e74098dbh
After marking it, we can now enable the swap file and allow the system to use it:
sudo swapon /swapfile
swap has been created successfully and the OS can use it.
Step 5 – Permanent setting swap memory on reboot
After implementing the above steps we are able to create the swap file for the current session. But if we reboot, the server will not retain the swap file. We can change this by adding the swap file entry to /etc/fstab file.
Before proceeding, back up the /etc/fstab file using the below command.
sudo cp /etc/fstab /etc/fstab.bak
Add the swap below command at the end of your /etc/fstab file:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
If you have skills in PHP programming and you want to enhance your career in this field, a PHP Certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.