Create Swap File

It's often necessary to add swap to a server, especially with a virtual private server with doesn't come with any. This tutorial will show you how to add a file to your system to act as swap.

If you don't have any swap, then your processes will be killed off as soon as you run out of memory. Your Linux box will automatically move the most infrequently accessed parts of memory to swap as your memory fills up. You can even adjust how aggressive your system will try to make use of the swap file by adjusting the swappiness.

I recommend only create swap files on local disks rather than networked locations such as an EBS. I'm still unsure about whether using an EBS for a swapfile is actually safe.

Steps

Create an empty file of the size you want your swap to be. You want this to be at a location on an SSD if possible.

sudo dd if=/dev/zero \
of=/swapfile \
bs=4K \
count=[250000*number of GB]

This should take a few seconds to a minute to complete.

Format the file to be a swap file:

sudo mkswap /swapfile 

Manually mount the swap

sudo swapon /swapfile

To make sure that the swapfile is automatically mounted next time your server boots up, open your /etc/fstab for editing.

sudo editor /etc/fstab

Add the following line:

/swapfile swap swap defaults 0 0

Extra Info - Removing and Re-adding Swap

Once you have added the swapfile to your fstab, you can use the following commands to unmount and mount all of your server's swap.

sudo swapoff -a
sudo swapon -a

Conclusion

That's it. You now have a swap file that will hopefully protect your processes from being killed due to lack of available memory.

References

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites. More info.