Swapfile creation

To create and activate a swap file on your Linux system.

To create and enable a swap file on your Linux system, follow these steps:

Create the Swap File

First, create a file that will be used as the swap space. In this example, we are creating a 2 GB swap file:

1
fallocate -l 2G /swapfile

Set the Correct Permissions

For security reasons, only the root user should have read and write access to the swap file. Set the appropriate permissions using the following command:

1
chmod 600 /swapfile

Set Up the Swap Area

Use the mkswap tool to configure the file as a Linux swap area:

1
mkswap /swapfile
  1. Activate the Swap File
    Enable the swap file so the system can start using it immediately:
1
swapon /swapfile

Make the Change Permanent

To ensure the swap file is activated automatically at system startup, you need to edit the /etc/fstab file. Open the file with a text editor, for example:

1
nano /etc/fstab

Add the following line to the file:

1
/swapfile swap swap defaults 0 0

Save and close the file. The swap file will now be permanently enabled.