Today I will be showing you how to create a swap file in Linux. There are many reasons why you may want to use a swap file, one of those reasons may be that you are using a droplet or VPS with a low amount of RAM.
So what is a swap file? Basically a swap file is like virtual memory saved on your hard drive that your desktop or server will use when it runs out of actual RAM. This is an easy bandaid that can prevent services from crashing for example MySQL on a cheaper droplet. For more information on swap files please checkout this article on Wikipedia.
Creating A Swap File In Linux
So lets get started with creating our swap file. First, we will create the actual swap file, the following command will create a 1GB swap file. You can adjust this to whatever size you want but 1GB should be enough for a basic droplet (like mine).
sudo fallocate -l 1G /swap
Next we will set the permissions and actually turn it into a swap file.
sudo chmod 600 /swap sudo mkswap /swap
Now we need to activate the swap file.
sudo swapon /swap
Finally, you need to add an entry into /etc/fstab so that the swap file will always be loaded after every reboot. If you don’t do this then this swap file will not be present when you reboot. You can manually add the line below or just run the echo command I provided.
/swap none swap sw 0 0
sudo echo '/swap none swap sw 0 0' >> /etc/fstab
Verify Your Swap File Exists
You can verify that your swap file now exists and is active by running either of the following commands.
sudo swapon --show free -h
I hope this quick and to the point guide helped, please don’t forget to like, comment, or share. Thanks!