Estimated reading time: 5 min
What is SWAP Partition
The purpose of writing this note is because the blog I recently set up crashed while previewing the theme ...
Firstly, we know that the Linux kernel caches files in memory to improve read and write efficiency and speed. This portion of memory is called Cache Memory.
Swap, also known as swap space, is like virtual memory. To cope with applications that require a large amount of memory, the system uses a portion of the disk as memory. When physical memory is insufficient, some data needs to be swapped to the swap space.
However, it's important to note that swap is slower in read and write speed compared to physical memory. The general recommendation is to have the swap space twice the size of physical memory (if physical memory is large enough, swap doesn't need to be enabled).
Steps to Enable
If you selected the SWAP partition during the installation process, you can skip this note.
Because the cloud server I used didn't have SWAP enabled when created, I need to manually set up and enable the partition to avoid various issues due to insufficient memory.
-
Create a swap file
You can use either fallocate or dd command to accomplish this:sudo fallocate -l 2G /swap
sudo dd if=/dev/zero of=/swap bs=1M count=2048
-
Set read and write permissions
For security reasons, the swap file should only be readable and writable by the root user. So, modify the permissions:sudo chmod 600 /swap
-
Make the swap file a swap partition
After creating the file, linux still don't know to use it as swap space, so it needs to be configured:sudo mkswap /swap
After setting up, enable the SWAP partition:
sudo swapon /swap
-
Adjust the tendency to use SWAP according to requirements
The system's Swappiness parameter controls the tendency to use swap space. The value ranges from 0 to 100, with lower values making the kernel prefer physical memory and higher values making the kernel prefer swap space.
Adjust this according to your needs, default is 60:sudo sysctl vm.swappiness=20
Add to /etc/sysctl.conf file to ensure permanent effect:
echo 'vm.swappiness=20' | sudo tee -a /etc/sysctl.conf
-
Mount SWAP partition permanently:
By default, swap is not automatically enabled when the system restarts. Edit the /etc/fstab file to make it permanent (can also be done with vim):echo '/swap none swap sw 0 0' | sudo tee -a /etc/fstab
Configuration Completed
With these steps, you should have successfully set up a 2GB swap partition on Ubuntu 20.04 system. When you use the free -h
command, you should see that the swap partition has been enabled.
When there's resource pressure and memory usage is under stress, enabling swap can help alleviate the pressure and ensure the system runs smoothly.