Create a Linux Swap File

Create a Linux Swap File

Create a Linux Swap File.webp


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.

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:
fallocate -l 1G /swap

2. Only the root user should be able to write and read the swap file. To set the correct permissions type:
chmod 600 /swap

3. Use the mkswap utility to set up the file as Linux swap area:
mkswap /swap

4. Enable the swap with the following command:
swapon /swap

5. To make the change permanent open the /etc/fstab file and append the following line:
/swap swap swap defaults 0 0

6. Reboot the system:
reboot

7. To verify that the swap is active, use either the swapon or the command as shown below:
swapon --show



How to remove Swap File
If for any reason you want to deactivate and remove the swap file, follow these steps:

1. Deactivate the swap by typing:
swapoff -v /swap

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

3. Delete the actual swap file using the rm command:
rm /swap

4. Reboot the system:
reboot
 
Top