How To Add Swap on Ubuntu

Introduction

One of the easiest way of increasing the responsiveness of your server and guarding against out of memory errors in your applications is to add some swap space. Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.

Basically, this gives you the ability to increase the amount of information that your server can keep in its working “memory”, with some caveats. The space on the hard drive will be used mainly when space in RAM is no longer sufficient for data.

Note

Although swap is generally recommended for systems utilizing traditional spinning hard drives, using swap with SSDs can cause issues with hardware degradation over time. Due to this consideration, we do not recommend enabling swap on VMs that utilizes SSD storage. Doing so can impact the reliability of the underlying hardware for you and your neighbors.

Check Available Space on the Hard Drive Partition

The typical way of allocating space for swap is to use a separate partition devoted to the task. However, altering the partitioning scheme is not always possible. We can just as easily create a swap file that resides on an existing partition.

Before we do this, we should be aware of our current disk usage. We can get this information by typing:

$ df -h

Create a Swap File

Now that we know our available hard drive space, we can go about creating a swap file within our filesystem.

We will create a file called swapfile in our root (/) directory. The file must allocate the amount of space we want for our swap file.

We can create a 4 Gigabyte file by typing:

$ sudo fallocate -l 4G /swapfile

Adjust the permissions on our file so that it isn’t readable by anyone besides root. Allowing other users to read or write to this file would be a huge security risk. We can lock down the permissions by typing:

$ sudo chmod 600 /swapfile

Set up the swap space by typing:

$ sudo mkswap /swapfile

Enable the file as swap space:

$ sudo swapon /swapfile

We can verify that the procedure was successful by checking whether our system reports swap space now:

$ sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        4194300 0       -1

Make the Swap File Permanent

We have our swap file enabled, but when we reboot, the server will not automatically enable the file. We can change that though by modifying the fstab file.

Edit the file with root privileges in your text editor:

$ sudo nano /etc/fstab

At the bottom of the file, add a line that will tell the operating system to automatically use the file you created:

/swapfile   none    swap    sw    0   0

Save and close the file when you are finished.