First create and intialize the file to hold the swap. In this example we create a 4GB swapfile:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
Set the appropriate permissions on the file: It should be readable and writable only by root.
sudo chmod 600 /swapfile
Format and enable the swapfile:
sudo mkswap /swapfile
sudo swapon /swapfile
In order to ensure that the swap is enabled at boot we can add an entry to /etc/fstab. You can add the line to fstab manually or using the command:
sudo bash -c "echo /swapfile none swap defaults 0 0 >> /etc/fstab"
👉 Source