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:

swapon -s
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

2. Let's change the default permissions so that only the system can read/write to this file

3. Creating swap area and enabling the swap space

4. Let's add this to the system as a permanent solution (so it works also after rebooting the server)

5. let's check if the swap is enabled and working

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

Last updated

Was this helpful?