How to Create a Swap File
On servers with low amounts of memory, it can be a good idea to create a swap file to prevent out of memory crashes. A swap file is a a designated space on your disk that can be used in addition to regular memory to give your system more, albeit much slower, memory.
Creating the swap file
To create the swap file, log into the console through SSH.
Once in, you will want to create the file that you would like to use with the following command:
dd if=/dev/zero of=/swapfile bs=1024 count=65535
Once you've created the file, you need to change it's permissions to keep it secure.
chmod 600 /swapfile
Now that your swap file is secure, you can turn it into a usable swap file:
mkswap /swapfile
Now it's ready to be used, so let's turn it on:
swapon /swapfile
That's all there is to it!
You can test to make sure that it was added by running the free -m command:
# free -m total used free shared buff/cache available Mem: 983 343 12 51 627 561 Swap: 63 0 63
If you would like to have your swapfile always mounted on boot, you will need to add it inside of /etc/fstab. You can add the following line to mount your swap file on boot.
/swapfile swap swap defaults 0 0