Skip to content
⚠️ Warning: Extraordinary electrical maintenance – Scheduled shutdown of the Cloud garr-ct1 region (Catania) from 22 to 29 July 2025. For more details, please read the maintenance notice.

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.

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.