In this tutorial I will show you how to set up a swap file on CentOS 8

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.

Before proceeding with this tutorial, check if your CentOS installation already has swap enabled by typing:

# swapon --show

If the output is empty, it means that your system does not have swap space enabled.

Create swap file

In this example, we will create a swap file of size 4GB using fallocate command.

# fallocate -l 4G /swap

Make it readable only by root user.

# chmod 600 /swap

Setup the file for swap space.

# mkswap /swap 
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=5c766682-0bec-4b16-a8aa-0756e5717792

Enable the swap file and add it to the system as a swap file.

# swapon /swap

Edit the /etc/fstab file and add the next line, to make the change permanent.

# nano /etc/fstab
/swap swap swap defaults 0 0

Save and exit.

Now we can reboot our server and verify swap.

# reboot
# swapon --show
/swap file 4G 0B -2

Or using the free command.

# free -h
total used free shared buff/cache available
Mem: 3.8Gi 140Mi 2.1Gi 16Mi 1.5Gi 3.3Gi
Swap: 4.0Gi 0B 4.0Gi

Removing a swap file

Execute the following command to disable the swap file.

# swapoff -v /swap

Remove /swap swap swap defaults 0 0 entry from the /etc/fstab file. 

Delete the swapfile file.

# rm /swap

We have learned how to configure swap space on CentOS 8 system.