Swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.
Swap space can take the form of either a dedicated swap partition or a swap file. Typically, when running Ubuntu on a virtual machine, a swap partition is not present, and the only option is to create a swap file.
This tutorial explains how to add a swap file on Ubuntu 20.04.
Before You Begin
Swap should not be seen as a replacement to physical memory. Since swap space is a section of the hard drive, it has a slower access time than physical memory. If your system constantly runs out of memory, you should add more RAM.
Generally, the size of the swap file depends on how much RAM your system has:
- Systems with less than 2 GB RAM – 2 times the amount of RAM.
- Systems with 2 to 8 GB RAM – the same size as the amount of RAM.
- Systems with more than 8 GB RAM – at least 4 GB of Swap.
Only root or user with sudo privileges can activate the swap file.