How to add Swap on Ubuntu 14.04

One of the easiest ways to improve server responsiveness and protect against memory errors in applications is to add Swap. Swap is an area on a hard drive where the operating system can temporarily store data that it can no longer hold in RAM.

Basically, this makes it possible to increase the amount of information that your server can store in its working “memory”, with some caveats. The hard disk space will be used mainly when the RAM space is no longer sufficient for data.

Information written to disk will be slower (there is no such problem in modern SSD disks) than information stored in RAM, but the operating system will prefer to continue working with application data in memory and use Swap for old data. In general, having swap space when your RAM is depleted is a good safety net.

In this tutorial, we’ll walk through how to create and enable a swap file on a 14.04 Ubuntu server.

Note While replacement is generally recommended for systems using traditional hard drives, using Swap with SSDs can cause hardware degradation issues over time. Due to this, we do not recommend enabling swap anyone if you are using SSD drives for storage. This can affect the reliability of the basic equipment for you and your neighbors. If you need to improve the performance of your server, we recommend updating your server. This will lead to better results overall and reduce the likelihood of contributing to hardware issues that could impact your service.

Check the system

Before we start, we will take a look at our operating system to see if we already have swap space available. We can have multiple swap files or a swap partition.

We can see if the system has any Swap configured by typing:

sudo swapon -s
Filename                Type        Size    Used    Priority

If you only get the table header in the output, as I showed above, you do not currently have swap enabled on your system.

Another, more familiar way of checking swopa using the utility freewhich shows us the use of system memory. We can see our current memory and Swap usage in megabytes by typing:

free -m
              total       used       free     shared    buffers     cached
Mem:          4714        147       4567          0          7         78
-/+ buffers/cache:         58       4248
Swap:            0          0          0

As you can see above, the total swap space on our system is 0. This is in line with what we saw with the previous command.

Checking free space on a hard disk partition

The typical way to allocate paging space is to use a separate section dedicated to this task. However, it is not always possible to change the partitioning scheme. We can just as easily create a swap file on an existing partition.

Before doing this, we need to be aware of our current disk usage. We can get this information by typing:

df -h
Filesystem      Size  Used Avail Use% Mounted on                                                                                                              
/dev/sda2        20G   19G  1.7G  92% /                                                                                                                       
devtmpfs        487M     0  487M   0% /dev                                                                                                                    
tmpfs           497M     0  497M   0% /dev/shm                                                                                                                
tmpfs           497M   51M  447M  11% /run                                                                                                                    
tmpfs           497M     0  497M   0% /sys/fs/cgroup                                                                                                          
/dev/sda1       240M  194M   30M  87% /boot                                                                                                                   
tmpfs           100M     0  100M   0% /run/user/0

As you can see in the first line, our hard disk partition has 55 gigabytes of free space, so we have a huge amount of space to work with. This is the size of an average VPS; however, actual usage can vary greatly.

While there are many opinions about the appropriate size of paging space, it really depends on your personal preference and application requirements. Typically, swop has an amount equal to or twice the amount of RAM on your system.

Since my system has 4GB of RAM, and doubling it will take up a significant portion of my disk space that we are not willing to part with, we will create 4GB of swap space to match my system.

Creating a swap file

Now that we know the information about the available free space on the hard disk, we can create a paging file in our file system.

We will create a file named swapfile in our root directory (/). The file should take up the amount of space that we want for our swap file. There are two main ways to do this:

Traditional, slow way

Traditionally, we would create a file with the space allocated using the command dd… This is a versatile utility to write to disk from one location to another location.

We can use it to write zeros to a file from a special device on Linux systems located at /dev/zero

We indicate the file size using the combination bs for block size and count for the number of blocks. What we assign to each parameter is almost completely arbitrary.

For example, in our example, we want to create a 4 gigabyte file. We can do this by specifying a block size of 1 GB and 4 blocks:

sudo dd if=/dev/zero of=/swapfile bs=1G count=4
4+0 records in
4+0 records out
4284867395 bytes (4.3 GB) copied, 17.6333 s, 431 MB/s

Check your command before pressing ENTER, as this has the potential to destroy data if you install the file in the wrong location.

We can find out that 4 gigabytes have been allocated by typing:

ls -lh /swapfile
-rw-r--r-- 1 root root 4.0G Feb 13 14:01 /swapfile

If you followed the command above, you may notice that it took quite a long time. In fact, you can see in the output that it took the system 18 seconds to create the file. This is because it has to write 4 gigabytes of zeros to disk.

If you want to know how to create a file faster, delete this file and follow below:

sudo rm /swapfile

Faster way

A quick way to get the same file is by using the program fallocate… This command creates a file with a size that is instantly allocated in advance, virtually without having to write dummy content.

We can create a 4 gigabyte file by typing:

sudo fallocate -l 4G /swapfile

The request will be returned to you almost immediately. We can check that the correct amount of space has been reserved by typing:

ls -lh /swapfile
-rw-r--r-- 1 root root 4.0G Feb 13 14:03 /swapfile

As you can see, our file is generated with the correct amount of space set.

Enabling the swap file

At the moment, our file has been created, but our system does not know what this file is and how to use it for exchange. We need to tell the system to format this swap file and then enable it.

Before doing this though, we need to set the permissions on our file so that it cannot be read by anyone other than root… Allowing other users to read or write to this file would be a huge security risk. We can block permissions by typing:

sudo chmod 600 /swapfile

Make sure the file has the required permissions by typing:

ls -lh /swapfile
-rw------- 1 root root 4.0G Feb 13 14:06 /swapfile

As you can see, only the columns for the root user have read and write flags enabled.

Now that our file is more secure, we can tell our system to create swap space by typing:

sudo mkswap /swapfile
Setting up swapspace version 1, size = 4184320 KiB
no label, UUID=f8f2edfg-crt5-sd45-gy7l-qwf6e3dfgt67

Our file is now ready to be used as swap space. We can enable it by typing:

sudo swapon /swapfile

We can verify that the procedure was successful by checking if our system is using swap now:

sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        4184322 0       -1

We now have a new swap file. We can use the utility free once again to confirm our findings:

free -m
              total        used        free      shared  buff/cache   available                                                                               
Mem:            992         315         263           0         414         484                                                                               
Swap:          2047         489        1558

Our swap has been successfully installed and our operating system will use it as needed.

Make a permanent swap file

We have a working swap file, but when we reboot the server, the swap will not work, it needs to be automatically enabled in the system. We can change this by modifying the file fstab

Modify the file with superuser privileges in a text editor:

sudo nano /etc/fstab

At the bottom of the file, add a line that tells the operating system to automatically use the generated swap file:

/swapfile   none    swap    sw    0   0

Save and close the file after making changes.

Your swap settings

There are several options that you can tweak that will have an impact on your system’s performance when dealing with swaps.

Параметр swappiness determines how often your system will swap data from RAM to paging space. This value ranges from 0 to 100, which is a percentage.

At values ​​close to zero, the kernel will not exchange data with the disk unless absolutely necessary. Remember that interacting with the paging file is “expensive” in that it takes much longer than interacting with RAM and can lead to significant performance degradation. Generally, systems do not rely on swap if you want to make your system faster.

Values ​​closer to 100 will try to swap more data in an attempt to free up as much free memory space as possible. Depending on the memory profile of your applications or what you are using your server, this may be better in some cases.

We can see the current swappiness value by typing:

cat /proc/sys/vm/swappiness
40

For the desktop, setting the swappiness to 10 is optimal for SSD drives. For a VPS system, we probably want to move it closer to 0.

We can set a different swappiness value with the command sysctl

For example, to set swappiness to 10, we could type:

sudo sysctl vm.swappiness=10
vm.swappiness = 10

This setting will not persist until the next reboot. We can set this value automatically on reboot by adding a line to our file /etc/sysctl.conf:

sudo nano /etc/sysctl.conf

At the bottom, you can add:

vm.swappiness=10

Save and close the file when you make changes.

Another parameter related to this value you can change this vfs_cache_pressure… This parameter determines how much the system will pick up for the inode cache and information trees over other data.

Basically, this is access to data about the file system. You can see the current value by asking proc to the filesystem:

cat /proc/sys/vm/vfs_cache_pressure
100

It is configured so that our system clears the inode information from the cache too quickly. We can set it to a more optimal value like 45 by typing:

sudo sysctl vm.vfs_cache_pressure=45
vm.vfs_cache_pressure = 45

Again, this is only true for our current session. We can change it by adding it to our config file as we did with our swappiness setup:

sudo nano /etc/sysctl.conf

At the bottom, add a line that defines your new value:

vm.vfs_cache_pressure = 45

Save and close the file when you make changes.

Output

Following the instructions in this guide gives you some temporary resolution to your RAM problem, in terms of your RAM usage. Swap space is incredibly useful in avoiding some common problems.

If you are running into OOM (out of memory) errors, or if you find that your system is unable to use the applications you want, the best solution is to optimize the application configuration or update the server. Setting up paging space, however, can give you more flexibility and can help you use a less powerful server.

Sidebar