Need help? Chat now!
Search results for:
Table of Contents
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:
Below are the steps that will walk you through creating 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 a swap using either fallocate or dd:
Creating a Swap File with fallocate
fallocate -l 1G /myswap
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:
dd if=/dev/zero of=/myswap count=1024 bs=1MiB
Step Two: Secure the swap file permissions:
chmod 600 /myswap
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.
/myswap none swap sw 0 0
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.
dd if=/dev/zero of=/myswap count=1024 bs=1MiB 1024+0 records in 1024+0 records out 1073741824 bytes (1.1 GB) copied, 2.15831 s, 497 MB/s
Written by Hostwinds Team / September 7, 2018