Adding SWAP (virtual ) memory
To prevent system process from crashing because of out-of-memory issues it is advised to add some extra space for swap memory.
Memory swapping is a computer technology that enables an operating system to provide more memory to a running application or process than is available in physical random access memory (RAM). https://www.enterprisestorageforum.com/hardware/what-is-memory-swapping/
Swap is a space on a disk that is used when the amount of physical RAM memory, so let's add this to our Ubuntu server

Before we start adding swap

let's check if your system has already enabled the swap by executing the following command:
1
swapon -s
Copied!
if instead of an empty response you get something similar to this, then it means you already have enabled swap space and you should skip this section and move to the next one.
Example of enabled swap
The SWAP should not be seen as a replacement for physical memory (RAM). Since swap space is a section of the hard drive, it has a significantly slower speed than regular RAM. If your server constantly runs out of RAM, you should be adding more RAM to it
If you have 4-16GB of RAM then you should add 8 GB of SWAP space, for larger servers you can double that.
    1.
    let's start by creating a SWAP file of 8GB
1
sudo fallocate -l 8G /swapfile
Copied!
2. Let's change the default permissions so that only the system can read/write to this file
1
sudo chmod 600 /swapfile
Copied!
3. Creating swap area and enabling the swap space
1
sudo mkswap /swapfile
2
sudo swapon /swapfile
Copied!
4. Let's add this to the system as a permanent solution (so it works also after rebooting the server)
1
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Copied!
5. let's check if the swap is enabled and working
1
sudo swapon --show
Copied!
now you can also check with the htop command and you should see the used and total swap space
6. Let's also increase the "swapiness" of the swap space - so the system is using this resource efficiently
1
sudo nano /etc/sysctl.conf
Copied!
Add this to the bottom of the file. /etc/sysctl.conf
1
vm.swappiness=10
2
vm.vfs_cache_pressure=50
Copied!
Save this file and exit. (Press CTRL + X, press Y and then press ENTER).
Last modified 6mo ago