Taken from a DigitalOcean tutorial.
Create and enable swapfile:
# create a 2GB file only accessible by root
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
# mark the file as a swap space
sudo mkswap /swapfile
# enable the swap file
sudo swapon /swapfile
Verify the swap is available:
sudo swapon --show
free -h
Make the swap permanent:
# backup fstab just in case
sudo cp /etc/fstab /etc/fstab.bak
# add the swapfile at the end of fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab