fbpx

Server Setup

How to configure swap file on CentOS, Ubuntu and other Linux OS

by , , revisited on


We have by far the largest RPM repository with NGINX module packages and VMODs for Varnish. If you want to install NGINX, Varnish, and lots of useful performance/security software with smooth yum upgrades for production use, this is the repository for you.
Active subscription is required.

In best-case scenarios, your server should have enough RAM to handle all its tasks. However, it may not be enough for various reasons:

  • expensive to add more RAM
  • sudden spikes in traffic cause heavy RAM usage by web server software

Thus, there is a need in extending virtual memory to use disk space. Which is called a swap file or swap partition.

It is best to have a swap partition rather than a swap file. Most dedicated server providers will allow you to configure swap partitions at the beginning of your server setup. Contrary, only a few VPS providers would allow you to configure a swap partition. Linode is one of such outstanding VPS providers, so we always recommend it.

The majority of VPS providers do not allow partitioning your VPS disk space. So your only option is to configure swap using a swap file. Here’s how to do it.

First, we need to know the size of the swap file we want. As a rule of thumb, this should be 1-1.5x the size of your installed RAM.

Let’s assume we have 768 Megabytes of RAM on a VPS instance. As such, we need a 768 Mb swap file.

Run these commands, copying each line one by one and diving by typing Enter, in your SSH client:

fallocate -l 768m /var/swap
chmod 600 /var/swap
mkswap /var/swap
swapon /var/swap
echo "/var/swap    none    swap    sw    0    0" >> /etc/fstab

The above commands will create a swap file under /var directory, adjusting file permissions and telling the system to immediately use it for swap. We also ensure to make the change persistent on reboots (last command).

Configure Swappiness

One of the major tweaks involved in configuring swap on any Linux system is adjusting swappinness. The higher the value, the more likely kernel would use swap when it needs more memory.

The following command can give insight into current value of swappiness. It is usually set pretty high (60), resulting in heavy use of swap by system:

sysctl -a | grep vm.swappiness

Since we want to avoid using slow virtual memory on a disk, the swappiness has to be adjusted to the lowest possible value. We don’t want to disable the use of the swap file at all, since we need it for those emergency times when RAM is not enough. So we set it to the value of 1:

sysctl -w vm.swappiness=1

Important note about 0 value

Adjusting to 0 is dangerous with Out of Memory errors, since recent kernel versions configured with a value of 0, would not use the swap file at all.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: