Add Memory Swap - CentOS

Difficulty: 2
Time: 30 minutes

If you’re trying to improve your server’s performance, adding swap space (or memory swap) is a powerful and relatively simply place to start.

Swap space is a dedicated portion of your server’s hard drive where the operating system can dump the contents of its RAM to, once the RAM gets full. To understand the real benefit of that, you need to be familiar with processor architecture - but here's a brief explanation:

  • RAM provides data to the processor quickly, which makes it very valuable.
  • Once your RAM is full it needs to either delete or move the data elsewhere.
  • Deleting the data from RAM means it must be found and retrieved from the hard drive (which is slow) the next time the data is requested.
  • By moving the data out of RAM and into a swap space instead of simply deleting it from RAM, it’s much faster to find the data the next time it’s requested.
  • Moving data from RAM to the swap space consumes the processor’s resources, so doing it continually will actually degrade your application’s performance. (This is known as swap thrashing.) To find the optimal swap rate, it requires tuning.

Lastly — though differences are minute, for the sake of clarity, this article walks you through create a swap file - not a swap partition. If you don't know what that means, don't worry about it.

Check current swap space usage

To prevent any issues when adding swap, first check that your system does not have already have a swap space enabled.

  • Find any active swap space on the drive:
    sudo swapon -s

You may get an output like this:

Filename                Type        Size    Used    Priority 

Or, you may get no output at all. Both mean you do not currently have any swap space enabled.

Here's an example of the results if your system does have configured swap:

Filename           Type         Size      Used  Priority 
/dev/sda7          partition    123450    100   -1

Check your available space

Now that you're ready to create a swap file, you need to find out space your server's hard drive has.

  • Check the amount of space available on the server:
    df -h

The results tell us the space usage and availability in M (for MB) or G (for GB). In this example, you have 40 GB available.

Filesystem      Size  Used Avail Use% Mounted on 
/dev/vda         50G  10G   40G   20% /                                    
none            4.0K     0  4.0K   0% /sys/fs/cgroup  
udev            2.0G   12K  2.0G   1% /dev            
tmpfs           396M  312K  396M   1% /run           
none            5.0M     0  5.0M   0% /run/lock      
none            2.0G     0  2.0G   0% /run/shm       
none            100M     0  100M   0% /run/user

The space you need depends on your requirements, but in general start with an amount equal to or double the amount of RAM on your system.

Create a swap file

Add swap space to your system by creating a file called swapfile in your root (/) directory and assigning it as swap. There are two commands you can use to create swap files:

  • fallocate
    Warning: The fallocate command has unresolved bugs in CentOS 7. CentOS 7 users should instead use the dd command to create their swap file.
  • dd

You only need to use one of these. We recommend using fallocate, but if it isn't supported on your file system, you can use dd instead.

Create a swap file using fallocate

  1. Create the file to be used for swap (for this example, we're adding a 4GB file):
    sudo fallocate -l 4G /swapfile
  2. Verify the correct amount of space was reserved.
    ls -lh /swapfile

Your output will look something like this:

-rw-r--r-- 1 root root 4.0G Jul 08 10:52 /swapfile

The file was added with the correct amount of space set aside.

Rarely, you get a failure message: fallocate failed: Operation not supported. This means your file system doesn't currently support fallocate (for example, ext3). Use the more traditional method with the dd command instead.

Create a swap file using dd

  1. To add a swap file the size of 4 GB, specify a block size bs of "1 GB" and a count of "4."
    Warning: Double-check this particular command because it has the potential to destroy data if the of command (output file) is pointed to the wrong location.
    sudo dd if=/dev/zero of=/swapfile bs=1G count=4
    You'll likely have to wait a few seconds, but once it generates, the output will look like:
    4+0 records in
    4+0 records out  
    4094967296 bytes (4.1 GB) copied, 18.0017 s, 215 MB/s
  2. Verify the file has been created on the server.
    ls -lh /swapfile
    Your output should look like:
    -rw-r--r-- 1 root root 4.0G Jul 08 10:53 /swapfile

The system created the file by writing 4 GB of zeroes to the disk.

Enable the swap file

Now that your swap file's been created, tell the system to format your file as swap, and then enable it.

  1. Lock the swap file's permissions so that only the root user can access it:
    sudo chmod 600 /swapfile
    When first created, swap files are readable by the world, so locking permissions prevents users from reading potentially sensitive information.
  2. Verify that the file has the correct permissions.
    ls -lh /swapfile
    Look for your output, which will resemble:
    -rw------- 1 root root 4.0G Jul 08 10:40 /swapfile
    This example confirms that only the root has read and write flags enabled.
  3. Format that file to create a swap space.
    sudo mkswap /swapfile
    If successful, the command will return something similar to this:
    Setting up swapspace version 1, size = 4194300 KiB
    no label, UUID=e2f1e9cf-c0a9-4ed4-b8ab-714b8a7d6944
  4. Mount/enable the swap space in the system.
    sudo swapon /swapfile

Make the swap file permanent

The last step is to integrate the swap file into your system's storage partitions and devices through fstab.

  1. Open fstab:
    sudo vim /etc/fstab
  2. At the end of the file, tell the operating system to automatically use the newly-created swap space.
    /swapfile none swap sw 0 0
  3. Save and close the file:
    :wq!

After the next reboot, the swap will be used automatically.

Tune the swap file

Now that you've created the swap file, you should work on tuning it to ensure it's giving you optimal performance. This isn't something you can easily do in one sitting, but is something you'll work on periodically as an admin.

Tuning your swap file means tinkering with the settings that make it perform a swap (that is, move content from RAM into your swap):

  • Swappiness
  • Cache pressure

Tuning is important because a poorly configured swap file can actually hurt your application's performance. The interactions between your system's RAM and the swap space are time-intensive (on a computational scale) and trying to swap too often (that is swap thrashing) can take more time than just retriving your data from your hard drive.

Swappiness

Swappiness is simply a setting that controls how often the swap file is used.

As a percentage between 0 and 100, a swappiness value of:

  • 0 means swapping processes out of physical memory are avoided until absolutely necessary (memory is depleted)
  • 100 means aggressively (almost instantly) moving swap processes out of physical memory and into the swap cache

You can change your server's swapiness in sysctl.conf.

  1. Open your /etc/sysctl.conf file:
    sudo vim /etc/sysctl.conf
  2. Add at the end of the file, add this text:
    vm.swappiness=10
  3. Save and close the file:
    :wq!

To tune your application, you can test changes to your swappiness value (between 0 and 100) and running performance tests.

Cache pressure

Another setting is the vfs_cache_pressure. Changing this setting could help when the VFS (virtual file system) cache objects (called dentry and inode_cache objects) consume a larger amount of memory versus other data like page cache and swap. Because VFS cache accesses data about the file system, it's frequently requested and very resource-intensive. Thus, it's a prime setting for your system to cache.

The higher the value of the vfs_cache_pressure, the more likely your server is to use its swap.

You can change your server's cache pressure (again) in sysctl.conf.

  1. Open /etc/sysctl.conf:
    sudo vim /etc/sysctl.conf
  2. Add at the end of the file, add this line:
    vm.vfs_cache_pressure = 50
  3. Save and close the file:
    :wq!

Like swappiness, you can work on increasing performance by testing different values here.

Verify swap space was enabled

Check your work with any of these three commands:

  • For a general report:
    sudo swapon -s
    Output may look like this:
    Filename                Type        Size    Used    Priority 
    /swapfile               file        4194300 0       -1
    You'll see that a swap file of 4 G.0 was added.
  • For a more detailed report:
    free -m
  • For a report on just swap details:
    cat /proc/meminfo | grep -i swap

Conclusion

Swapping enables you to increase the amount of information that your server can keep in its working memory. Even though reading from and writing to swap is slower than using actual memory, swap can be a good safety net for the times your server is low on memory.

However, it's important to remember to periodically tune your swap file to ensure you're getting the most out of it.


Czy ten artykuł był pomocny?
Thanks for your feedback. To speak with a customer service representative, please use the support phone number or chat option above.
Cieszymy się, że udało się nam pomóc! Czy coś jeszcze możemy dla Ciebie zrobić?
Przykro nam z tego powodu. Tell us what was confusing or why the solution didn’t solve your problem.