Linux divides its physical memory (or the RAM, random access memory) into chucks of memory called pages. When a program require more memory and there isn’t enough physical memory, Linux will starts moving out inactive pages and store them on hard disk.
The process of moving out the pages for physical memory to disk is called swapping. The size of “memory on disk” is depending on the swap file size. The combination of physical memory and the “memory on disk” is called virtual memory. Therefore, you can have virtually unlimited memory.
Swapping has it disadvantage – it is slow when Linux need to keep swapping in and out of memory pages. It is slow because of the disk speed limitation. But if you have a server running with SSD disk (solid-state disk), you may not feel the pain. However, the process is required to make sure the operating system can works under memory pressure.
Check for Existing Swap File
Execute the following command to check for the existing swap space:
swapon -s
Check for Available Disk Space
Execute the following command to check for disk space availability.
df -h
Create Swap File
Execute the following command to create a swap file of size 1Gb. The following command will write zero values with block size 1024 bytes 1024k times to file “swapfile”.
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
Enable Swap File
Execute the following command to make the file a swap space.
sudo mkswap /swapfile
Start Using Swap File
Execute the following command to let the operating system know the swap file is now ready to use.
sudo swapon /swapfile
Set Swap File Permission
Execute the following commands to ensure the swap file has the correct file permission:
chown root:root /swapfile
chmod 0600 /swapfile
Done
Execute swapon -s
to ensure the swap file is being used.
Enable Swap File Durinn Boot Up
When the machine reboot, operating system will not use the swap file again. You can ensure that the swap is permanently loaded by adding it to the fstab file. Edit the file “/etc/ftab” and add the following line:
/swapfile swap swap defaults 0 0
Leave a Reply