Create a Linux swap file
Swap is space on a disk that is reserved for use as virtual memory. When a Linux® server runs out of memory, the kernel can move inactive processes into swap space to make room for active processes in the working memory.
By default, a swap partition is not present on Cloud Servers, but you can add swap to a server by allocating a swap file. The performance of a swap file is similar to that of a swap partition. However, using a swap file makes it easier to control the swap size without repartitioning a volume. You can control how aggressively the server uses this swap space by modifying the system's swappiness value.
The steps below show how to create a swap file on Linux and modify a system's swappiness value.
How do I add a swap file?
The following steps show how to add 1GB of swap to your server:
-
Check the current status of swap using any/all of the following commands:
swapon -s free -m cat /proc/swaps
-
Create the file that you want to use for swap using either of the following commands:
sudo fallocate -l 1G /mnt/1GB.swap # or sudo dd if=/dev/zero of=/mnt/1GB.swap bs=1024 count=1048576
-
Format the swap file by entering the following command:
sudo mkswap /mnt/1GB.swap
-
Ensure permissions on the file is readable, writeable, and owned by root:root only. If not, use:
sudo chown root:root /mn/t1GB.swap sudo chmod 600 /mnt/1GB.swap
-
Add the following line to the end of
/etc/fstab
to make the change permanent:/mnt/1GB.swap none swap sw 0 0
-
Validate your fstab entry by instructing swapon to use fstab to mount all swap definitions by entering the following command:
sudo swapon -a
-
Check for the correct and expected amount of swap by using commands listed in step 1
-
To change the swappiness value, add the following line to the file at
/etc/sysctl.conf
:vm.swappiness=10
Start with a value of 10 and increase if it as necessary. A typical default value for swappiness is 60. The higher the number (up to 100), the more often the system uses swap.
The degree to which swappiness affects performance depends on how your memory is currently used. We recommend that you experiment to find an optimal value. At 0, the system only uses the swap file when it runs entirely out of memory. Higher values enable the system to swap idle processes out in order to free memory for disk caching, potentially improving overall system performance.
-
Optional: Reboot the server to ensure that the changes survive.
Updated 3 days ago