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. In most cases, when running Linux on a virtual machine, a swap partition is not present, so the only option is to create a swap file.
This tutorial was tested on Linux systems with Ubuntu 18.04 and CentOS 7, but it should work with any other Linux distribution.
How to add Swap File
Follow these steps to add 1GB of swap to your server. If you want to add 2GB instead of 1 GB, replace
1G
with 2G
.
1. Create a file that will be used for swap:
sudo fallocate -l 1G /swapfile
If
faillocate
is not installed or if you get an error message saying fallocate failed: Operation not supported
then you can use the following command to create the swap
file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
2. Only the root user should be able to write and read the swap file. To set the correct permissions type:
sudo chmod 600 /swapfile
3. Use the
mkswap
utility to set up the file as Linux swap area:sudo mkswap /swapfile
4. Enable the swap with the following command:
sudo swapon /swapfile
To make the change permanent open the
/etc/fstab
file and append the following line:
/etc/fstab
/swapfile swap swap defaults 0 0
5. To verify that the swap is active, use either the
swapon
or the free
command as shown below:sudo swapon --show
Output
NAME TYPE SIZE USED PRIO
/swapfile file 1024M 507.4M -1
sudo free -h