Server Setup

Configure Swap file on CentOS

by ,


We have by far the largest RPM repository with dynamic stable NGINX modules and VMODs for Varnish 4.1 and 6.0 LTS. If you want to install NGINX, Varnish and lots of useful modules for them, this is your one stop repository to get all performance related software.
You have to maintain an active subscription in order to be able to use the repository!

In best case scenarios, server should had 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 swap file, or swap partition.

Most of the major VPS providers, like DigitalOcean and Vultr, allow you to configure swap with your Linux OS. The best way to do this on a dedicated server is having a separate partition just for Swap. In case of VPS, we need to configure a swap file.

First, we need to know the size of 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 CentOS 6 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 into 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 use of swap file at all, since we need it for those emergency times when RAM is not enough. So we set it to value of 1:

sysctl -w vm.swappiness=1

Important note about 0 value

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

Leave a Reply

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