Don’t have swap partition? Here’s how to create a swap file instead for your Linux.
The swap space is used when your RAM memory is full. Linux moves inactive pages in memory to the swap, if the system need more memory resources while RAM is full. This is useful for machines with a small RAM memory size.
As well, for desktop computers need hibernate function. The swap can be used for saving your current works. It moves all the contents from memory into swap area and shuts down your machine. Next time you boot the computer, it reverts the system status exactly as it was.
Why using Swap file:
We usually create a swap partition on hard drive while installing Linux. But for those with large amounts of RAM (16 GB or even 32 GB+), you may skip the swap space with confidence. However, you may want Linux to sleep to the disk (hibernate).
Or you may upgrade the amount of RAM, and need more swap space while the previous one is not enough.
So a Swap file can be created to take place or work together with the Swap partition. And it is virtually as fast as swap partition, though some Linux systems, e.g., Fedora, recommends swap partitions.
And swap file is flexible. You can create it on any mounted partition, set it to any desired size, and remove it whenever you want.
How to Create / Add Swap File
This tutorial is tested and works on Debian 11 Bullseye and Ubuntu 22.04, though it should work on all current Linux distributions.
1.) Firstly, open terminal or connect to your server console. Run command to pre-allocate disk space on Linux partition for a file:
sudo dd if=/dev/zero of=/swapfile count=4096 bs=1MiB
NOTE: In the command it allocates 4GB (4096×1 MB) for the “swapfile” file in root directory. Change the size accordingly, usually as large as RAM size (or double for less than 2GB RAM).
2.) Next change the file permission: read & write for owner (root), and none for all others. To do so, run command:
sudo chmod 600 /swapfile
3.) Now you can set the file as a Linux swap area via command:
sudo mkswap /swapfile
4.) And finally make it work by running command:
sudo swapon /swapfile
5.) To make it permanent, you have to write a new line ‘/swapfile none swap sw 0 0’ into the /etc/fstab file, so Linux will automatic mount the file as swap area on startup.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
OK, now you can check the status of the swap space via command:
sudo swapon --show
cat /proc/swaps, even
free -h command instead to see the swap area usage.
How to Remove Swap File:
Removing swap file is also easy. You need to firstly disable it for paging and swap‐ping, by running command:
sudo swapoff -v /swapfile
Next remove the line in “/etc/fstab” file. You may firstly backup the file via command:
sudo cp /etc/fstab /etc/fstab.bak
Then run command to remove the line that contains ‘swapfile’.
sudo sed -i '/swapfile/d' /etc/fstab
You can finally remove the /swapfile file:
sudo rm /swapfile
That’s all. Enjoy!