abhai
18 June 2023
To create swap space on Linux, you can follow these steps:
- Check the available disk space: Open a terminal and run the command `df -h` or `sudo swapon --show` or `free -h` to view the current disk space usage. Ensure that you have enough free space for the swap file.
- Create a swap file: Use the `fallocate` command to create a swap file of the desired size. For example, to create a 2GB swap file, run the following command:
sudo fallocate -l 2G /swapfile
- Set appropriate permissions: Change the permissions of the swap file to restrict access only to the root user:
sudo chmod 600 /swapfile
- Configure the swap file: Enable the swap file by turning it into a swap area using the `mkswap` command:
sudo mkswap /swapfile
- Activate the swap file: Activate the swap file using the `swapon` command:
sudo swapon /swapfile
- Make the swap file persistent: To ensure that the swap file is automatically enabled on system boot, open the `/etc/fstab` file in a text editor (e.g., `sudo nano /etc/fstab`) and add the following line at the end of the file:
/swapfile none swap sw 0 0
You can also run the following command to add this line to the fstab file:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Don't forget to take a backup of your fstab file:
sudo cp /etc/fstab /etc/fstab.bak
-
Verify the swap space: Run the `free -h` command to verify that the swap space is active and available. It should look something like this.
That's it! You have successfully created swap space on Linux using a swap file. The system will now use this swap space as additional virtual memory when required.