Search The Hostwinds Guides Knowledge Base

How To Create Linux Swap File

Share This Article

Swap is an allocated space on Linux that has been reserved to be used as virtual memory. When a Linux server runs out of memory inactive processes can be moved into the virtual memory to make room for active processes in the working memory.

This feature is not turned on by default, but can be turned on by allocating a swap file. Performance on the swap file is very similar to that of a swap partition. However, it is easier to control the swap size without repartitioning. How actively the server will rely on the swap space can also be controlled by adjusting the system’s swappiness value.

As our VPSes and dedicated servers provide root by default, all commands are assumed to be running as root:

How To Create Swap In Linux

Below are the steps will walk you through the creation of a swap file and how to modify the swappiness value. To add 1GB of swap to your server, for example, follow this guide:

Step One: To create the file to be used for swap using either fallocate or dd:

Creating a Swap File with fallocate

the -l option allows you to set the length, 1 Gigabyte in this example

Alternatively, you can use dd to create a blank 1GB file:

Step Two: Secure the swap file permissions:

Format the file for swap.

Step Three: Add the file to the system as a swap file.

Step Four: Add this line to the end of /etc/fstab  to make the change permanent.

Step Five: To change the swappiness value edit /etc/sysctl.conf  and add the following line.

Start with a value of 10 and increase if needed. A typical default value for swappiness is 60. The higher the number (up to 100), the more often swap is utilized.

How much swappiness affects performance depends on how your memory is being used, so experiment to find an optimal value. At 0 the swap file will only be used when the system runs completely out of memory. Higher values let the system swap idle processes out to allow the system to free memory for disk caching, potentially improving overall system performance.

Step Six: Check that the swap file was created.

Reboot the server to ensure that the changes go into effect.

In most cases, you only need access to the swap partition as the root user.