Programster's Blog

Tutorials focusing on Linux, programming, and open-source

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.


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=[262144 * number of GiB]

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

Set permissions and format the file to be a swap file:

sudo chmod 600 /swapfile
sudo chown root:root /swapfile
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


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


Last updated: 4th January 2023
First published: 16th August 2018