Add Memory Swap - Ubuntu or Debian 7

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 swap space on the drive:
    sudo swapon -s

If the results are empty, the output looks similar to the following example, and you currently have no swap space enabled:

Filename                Type        Size    Used    Priority

If your system does have configured swap, the results look like this example:

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

This command shows the free space on your hard disk. In the following example, you have 40 GB available. Make sure that there is enough free space for your swap file. The space you need depends on your requirements but, in general, an amount equal to or double your system's RAM.

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      

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
  • 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

You can gain more file space with fallocate, a command used to manipulate file space. The fallocate command creates a file of a preallocated size instantly without initializing any of it, versus the dd command, which takes longer because it has to write zeroes as dummy contents.

Create a swap file using fallocate

  1. Create the file to be used for swap. For this example, we add a 4 GB file:
    sudo fallocate -l 4G /swapfile
  2. Verify that the correct amount of space was reserved:
    ls -lh /swapfile
    This result shows that the file was added with the correct amount of space set aside:
    -rw------- 1 root root 4.0G Jul 08 10:52 /swapfile

If you get a failure message saying fallocate failed: Operation not supported, your file system doesn't currently support fallocate (for example, ext3). Use the more traditional way with the dd command instead. (This situation should be rare.)

Create a swap file using dd

In this example, we'll add a swap file of a different size, 1 GB, in order to accommodate smaller-sized servers.

  1. Add the 1 GB swap file by specifying a block size bs of 250 MB and a count of 4.
    Warning: Remember to double check your instructions! This command has the potential to destroy data if of (output file) points to the wrong location.
    sudo dd if=/dev/zero of=/swapfile bs=250M count=4
    After a few seconds, the generated output looks like this:
    4+0 records in
    4+0 records out
    1048576000 bytes (1.0 GB) copied, 1.47414 s, 711 MB/s
  2. Verify that the file was created on the server:
    ls -lh /swapfile
    If the file was created properly, the command returns something similar to this:
    -rw-r--r-- 1 root root 1.0G Jul 08 10:30 swapfile

Enable the swap file

Now that the file is created, format it 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
    The command returns something similar to this:
    -rw------- 1 root root 4.0G Jul 08 10:40 /swapfile
    This 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
  5. Verify that the swap space was enabled by checking the system reports:
    sudo swapon -s
    The command returns something similar to this:
    Filename Type Size Used Priority
    swapfile file 4194300 0 -1

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 fstab file, add this line to tell the system to automatically use the newly created swap space:
    /swapfile none swap sw 0 0
  3. Save and close the file:

After the next restart, the swap is 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 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 /etc/sysctl.conf:
    sudo vim /etc/sysctl.conf
  2. Add at the end of the file, add this line:
  3. Save and close the file:

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:

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

Verify that swap space was enabled

Check your work with any of these three commands:

  • swapon -s command:
    sudo swapon -s
    Output may look like this:
    Filename                Type        Size    Used    Priority 
    /swapfile               file        4194300 0       -1
    You'll see that a swapfile 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


Swapping can be beneficial in allowing your system to harness more memory than originally available. It's a viable option before having to optimize your application configurations, add more RAM, or upgrade your server.

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

Помогла ли вам эта статья?
Благодарим вас за отзыв. Чтобы связаться с сотрудником службы поддержки клиентов, позвоните по номеру этой службы или воспользуйтесь опцией чата выше.
Мы рады вам помочь! У вас остались вопросы?
Приносим извинения. Расскажите нам, какие затруднения вы испытываете или почему рекомендованное решение не помогло устранить проблему.