How to Add Swap Space (in Linux)

How to Add Swap Space (in Linux)

Why Add Swap Space?

Adding swap space is one of the easiest ways to increase the responsiveness of your servers and guard against out of memory errors, or errors caused by your server’s memory being full. This tutorial will walk through how to add swap space to your Linux server.

What Is Swap Space?

Swap space is an allocated area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in physical memory (RAM).

Swap space is used when your system decides that it needs to use the physical memory and there is insufficient unused physical memory available. If the system happens to need more memory resources or space, inactive pages in the physical memory are then moved to the swap space freeing up that physical memory for other uses.

How to Add Swap Space

NOTE: This tutorial was designed and tested for use on Ubuntu 14.04. Based upon the specific flavor and version of Linux used, there may be changes to particular commands or steps. The overall steps and commands should be close.

NOTE: This tutorial also expects that you have root access to execute the commands necessary, if not, you’ll need to have sudo access and prefix all commands with sudo.

Step 1. Check the System for Existing Swap Space

Before we begin, it is recommended to look at the operating system to see if swap space has already been defined and is available. It is possible to have multiple swap files or swap partitions, but typically one should be sufficient.

We can see if the system has any configured swap space by using the swapon command. The -s flag will display a summary of swap usage and availability.

swapon -s

If you only get back the header of the table, as shown below, or if nothing is returned by the command then you do not currently have any swap space enabled.

Filename                Type        Size    Used    Priority

Step 2. Verify Space Available For Use As Swap Space

Typically when we allocate swap space for a system, a separate partition devoted only to the swap space is used. Sometimes; however, altering the partitioning scheme is not always possible. This means that we can just as easily create a swap file that resides on an existing disk partition. This tutorial will use an existing disk partition when allocating swap space rather than allocating swap space to its own distinct partition.

Before allocating swap space, we should find out our current disk usage. This information can be retrieved by using the df, which will report the amount of available disk space being used by the file systems. The -h flag will tell the command to print sizes in a human readable format.

df -h

This will return a list of the file systems and the available disk space available on each, an example of which is shown below:

Filesystem      Size  Used Avail Use% Mounted on
/dev/vzfs       983G  790G  157G  84% /
none            2.0G  4.0K  2.0G   1% /dev

As you can see on the second (highlighted) line, we have a huge amount of free space to work with, 157GB to be exact. Your actual usage may be different, but you’ll want to make sure you have enough to allocate to your desired swap file.

There are many opinions about the appropriate size of a swap file, but in truth, it really depends on what you’re trying to achieve. Generally, an amount equal to or double the amount of physical memory on your system is a good starting point.

For the purposes of this tutorial, I’ll create a swap space of 1GB.

Step 3. Allocating Space To The Swap File

The next step is to create a swap file that we can use for swap space. We can allocate space to our swap file by using the fallocate command. This command creates a file of the specified preallocated size instantly.

Go ahead a create a 1GB swap file, within the root (/) directory by executing the following command:

fallocate -l 1G /swapfile

Once the prompt is returned to you, you’ll need verify that the correct amount of space was reserved by typing:

ls -lh /swapfile

You should see output allowing you to verify the space desired was properly allocated. An example output is shown below:

-rw-r--r-- 1 root root 1.0G Dec 28 11:14 /swapfile

Step 4. Enabling the Swap File

Now that we have a swap file created, we need to notify the system that this file is to be used for swap space. We want to tell our system to format this file as swap and then enable it.

Before doing that, the permissions on the swap file need to be adjusted so that it isn’t readable by anyone besides root, as allowing other users to read or write to this file would be a huge security risk.

The following command can be used to lock down the permissions on the swap file:

chmod 600 /swapfile

Now, verify that the file has the correct permissions by typing:

ls -lh /swapfile

You should see output that indicates only root is able to read and write to the swapfile, as shown below:

-rw------- 1 root root 1.0G Dec 28 11:14 /swapfile

At this point we want to tell the system to setup the swap space. We can do so by using the mkswap command.

mkswap /swapfile

This will return a result similar to the following, indicating that the swapspace has been setup, with the size, swapspace version, label, and UUID given.

Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=8d8135f8-ffd2-469f-b0d5-12984145ed9e

Once the system has setup and prepared the swap space, we can now enable the swap space by using the swapon command:

swapon /swapfile

Validate the swapon command was successful by checking whether the system is now reporting swap space.

swapon -s

You should see output similar to below, showing the swapfile details.

Filename                Type        Size    Used    Priority
/swapfile               file        1048572 0       -1

Technically, the newly created swap space has been setup successfully and the operating system can and will begin to use it as necessary; however, even though the swap file has been enabled, upon reboot the server will not automatically enable the file. We need to take additional steps and modify the fstab file to ensure the swap file is enabled upon server startup.

Setup the Swap File to Be Permanent

We have our swap file enabled, but when we reboot, the server will not automatically enable the file. We can change that by modifying the fstab file.

nano /etc/fstab

At the bottom of the file, add a line to indicate to the operating system to startup and use the swapfile we created previously:

/swapfile   none    swap    sw    0   0

Save and close the file when you are finished, your swap file is, and will now be enabled upon system restart.

Tweak Swappiness & VFS Cache Pressure Settings

There are a few options that can be configure to improve your system’s performance when dealing with swap space.

The swappiness parameter configures how often your system will swap data out of RAM and into swap space. This is a value between 0 and 100 that represents a percentage. A low value causes the kernel to avoid swapping; a higher value causes the kernel to try to use swap space. The default swappiness parameter value is 60. Depending on your applications’ memory profile or what you are using your server for, you’ll want to tweak this value accordingly.

We can see the current swappiness value querying the proc filesystem:

cat /proc/sys/vm/swappiness

This will return an integer value, as shown below:

60

For a server or VPS system, we want to move it closer to 0, and tell the system to use RAM as much as possible, and only use swap when it is absolutely necessary. We can set the swappiness parameter to a different value by using the sysctl command.

I’ve found a good value for my servers is to set the swappiness paramter value to 10:

sysctl vm.swappiness=10

The following result should now be displayed if the sysctl executed successfully.

vm.swappiness = 10

This setting will persist until the next reboot, as with the swap file, we need to set this value automatically at restart. You’ll want to modify the /etc/sysctl.conf file, and add the swappiness directive at the bottom.

nano /etc/sysctl.conf

At the bottom, add the following parameter:

vm.swappiness=10

Another related value that you might want to modify is the vfs_cache_pressure. This percentage value controls the tendency of the Linux kernel to reclaim the memory which is used for the caching of directory and inode objects. The default vfs_cache_pressure value on most systems is initially set to 100.

You can see the current value by querying the proc filesystem again:

cat /proc/sys/vm/vfs_cache_pressure

This will return an integer value, as shown below:

100

We want the system to cache inode and directory information, but having the vfs_cache_pressure value set to 100 can removes directory and inode information from the cache a little too quickly. We want to target a more conservative setting like 50 by typing:

sysctl vm.vfs_cache_pressure=50

Upon successfully executing the sysctl command, you’ll be returned a response showing the new vfs_cache_pressure value, as shown below:

vm.vfs_cache_pressure = 50

As with the swappiness value, the vfs_cache_pressure will only remain valid for our current session. We will need to add it to the /etc/sysctl.conf configuration file to make it permanent upon system restart.

nano /etc/sysctl.conf

At the bottom, add a vfs_cache_pressure line that specifies the new vfs_cache_pressure value setting:

vm.vfs_cache_pressure = 50

Save and close the file.

Swap Space Setup Complete!

You’re system is now configured to use space.

Author: daharveyjr

I’m a solution architect responsible for the design, development, implementation, testing, and maintenance of e-commerce operations and applications using the Hybris and WebSphere Commerce product suites and other web technologies such as Java, J2EE/JEE, Spring, PHP, WordPress and more. Twitter | Facebook | Google+ | LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *