Member-only story
How to create a Linux swap file
When you first installed your Linux distribution, you forgot to create a properly sized swap partition. Someone could be panicked, since resizing a partition under some conditions can be very difficult, but in our help comes the swap file.
It’s very simple to create a swap file, with a couple of shell commands you will be out of troubles. First of all, we check our swap status.
free -h
As we can see, we have only 974Mi allocated to swap. We want to allocate the swap file under the root of our file system, in a file called “swapfile”, and we desire that the file size will be 4G.
sudo fallocate -l 4G /swapfile
Now we need to properly set the permissions for the swapfile.
sudo chmod 600 /swapfile
Then, we use the mkswap command to set up a swap file in our desired path.
sudo mkswap /swapfile
The swap file is ready to be used. To activate the swap, we need to use swapon.
sudo swapon /swapfile
Checking again our swap status, we can see that the size changed from 974Mi to 5Gi. If we want to make the change permanent, we must edit the fstab file.
I’m using nano to edit the /etc/fstab file, but feel free to use the text editor of your choice.
sudo nano /etc/fstab
Now, add the following line to the file:
/swapfile none swap sw 0 0
If you are using nano, save the file using CTRL+O, exit and…the magic is done! :)