Introduction

One of the easiest way of increasing the responsiveness of your server and guarding against out-of-memory errors in applications is to add some swap space. In this guide, we will cover how to add a swap file to an Ubuntu 16.04 server.

Warning

Although swap is generally recommended for systems utilizing traditional spinning hard drives, using swap with SSDs can cause issues with hardware degradation over time. Due to this consideration, we do not recommend enabling swap on DigitalOcean or any other provider that utilizes SSD storage. Doing so can impact the reliability of the underlying hardware for you and your neighbors. This guide is provided as reference for users who may have spinning disk systems elsewhere.

If you need to improve the performance of your server on DigitalOcean, we recommend upgrading your Droplet. This will lead to better results in general and will decrease the likelihood of contributing to hardware issues that can affect your service.

What is Swap?

Swap is an 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 RAM. Basically, this gives you the ability to increase the amount of information that your server can keep in its working "memory", with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

The information written to disk will be significantly slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fall back for when your system's RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

Check the System for Swap Information

Before we begin, we can check if the system already has some swap space available. It is possible to have multiple swap files or swap partitions, but generally one should be enough.

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


  • sudo swapon --show

If you don't get back any output, this means your system does not have swap space available currently.

You can verify that there is no active swap using the free utility:


  • free -h

Output
total used free shared buff/cache available
Mem: 488M 36M 104M 652K 348M 426M
Swap: 0B 0B 0B

As you can see in the "Swap" row of the output, no swap is active on the system.

Check Available Space on the Hard Drive Partition

The most common way of allocating space for swap is to use a separate partition devoted to the task. However, altering the partitioning scheme is not always possible. We can just as easily create a swap file that resides on an existing partition.

Before we do this, we should check the current disk usage by typing:


  • df -h

Output
Filesystem Size Used Avail Use% Mounted on
udev 238M 0 238M 0% /dev
tmpfs 49M 624K 49M 2% /run
/dev/vda1 20G 1.1G 18G 6% /
tmpfs 245M 0 245M 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 245M 0 245M 0% /sys/fs/cgroup
tmpfs 49M 0 49M 0% /run/user/1001

The device under /dev is our disk in this case. We have plenty of space available in this example (only 1.1G used). Your usage will probably be different.

Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point. Another good rule of thumb is that anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

Create a Swap File

Now that we know our available hard drive space, we can go about creating a swap file within our filesystem. We will create a file of the swap size that we want called swapfile in our root (/) directory.

The best way of creating a swap file is with the fallocate program. This command creates a file of a preallocated size instantly.

Since the server in our example has 512MB of RAM, we will create a 1 Gigabyte file in this guide. Adjust this to meet the needs of your own server:


  • sudo fallocate -l 1G /swapfile

We can verify that the correct amount of space was reserved by typing:


  • ls -lh /swapfile

  • -rw-r--r-- 1 root root 1.0G Apr 25 11:14 /swapfile

Our file has been created with the correct amount of space set aside.

Enabling the Swap File

Now that we have a file of the correct size available, we need to actually turn this into swap space.

First, we need to lock down the permissions of the file so that only the users with root privileges can read the contents. This prevents normal users from being able to access the file, which would have significant security implications.

Make the file only accessible to root by typing:


  • sudo chmod 600 /swapfile

Verify the permissions change by typing:


  • ls -lh /swapfile

Output
-rw------- 1 root root 1.0G Apr 25 11:14 /swapfile

As you can see, only the root user has the read and write flags enabled.

We can now mark the file as swap space by typing:


  • sudo mkswap /swapfile

Output
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

After marking the file, we can enable the swap file, allowing our system to start utilizing it:


  • sudo swapon /swapfile

We can verify that the swap is available by typing:


  • sudo swapon --show

Output
NAME TYPE SIZE USED PRIO
/swapfile file 1024M 0B -1

We can check the output of the free utility again to corroborate our findings:


  • free -h

Output
total used free shared buff/cache available
Mem: 488M 37M 96M 652K 354M 425M
Swap: 1.0G 0B 1.0G

Our swap has been set up successfully and our operating system will begin to use it as necessary.

Make the Swap File Permanent

Our recent changes have enabled the swap file for the current session. However, if we reboot, the server will not retain the swap settings automatically. We can change this by adding the swap file to our /etc/fstab file.

Back up the /etc/fstab file in case anything goes wrong:


  • sudo cp /etc/fstab /etc/fstab.bak

You can add the swap file information to the end of your /etc/fstab file by typing:


  • echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Tweak your Swap Settings

There are a few options that you can configure that will have an impact on your system's performance when dealing with swap.

Adjusting the Swappiness Property

The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage.

With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are "expensive" in that they take a lot longer than interactions with RAM and they can cause a significant reduction in performance. Telling the system not to rely on the swap much will generally make your system faster.

Values that are closer to 100 will try to put more data into swap in an effort to keep more RAM space free. Depending on your applications' memory profile or what you are using your server for, this might be better in some cases.

We can see the current swappiness value by typing:


  • cat /proc/sys/vm/swappiness

Output
60

For a Desktop, a swappiness setting of 60 is not a bad value. For a server, you might want to move it closer to 0.

We can set the swappiness to a different value by using the sysctl command.

For instance, to set the swappiness to 10, we could type:


  • sudo sysctl vm.swappiness=10

Output
vm.swappiness = 10

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


  • sudo nano /etc/sysctl.conf

At the bottom, you can add:

/etc/sysctl.conf
vm.swappiness=10

Save and close the file when you are finished.

Adjusting the Cache Pressure Setting

Another related value that you might want to modify is the vfs_cache_pressure. This setting configures how much the system will choose to cache inode and dentry information over other data.

Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it's an excellent thing for your system to cache. You can see the current value by querying the proc filesystem again:


  • cat /proc/sys/vm/vfs_cache_pressure

Output
100

As it is currently configured, our system removes inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing:


  • sudo sysctl vm.vfs_cache_pressure=50

Output
vm.vfs_cache_pressure = 50

Again, this is only valid for our current session. We can change that by adding it to our configuration file like we did with our swappiness setting:


  • sudo nano /etc/sysctl.conf

At the bottom, add the line that specifies your new value:

/etc/sysctl.conf
vm.vfs_cache_pressure=50

Save and close the file when you are finished.

Conclusion

Following the steps in this guide will give you some breathing room in cases that would otherwise lead to out-of-memory exceptions. Swap space can be incredibly useful in avoiding some of these 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 need, the best solution is to optimize your application configurations or upgrade your server.

</div>

How To Add Swap Space on Ubuntu 16.04的更多相关文章

  1. Ubuntu 16.04系统布署小记

    前段时间趁着双11打折,又将阿里云主机续费了3年.之前布署的系统是Ubuntu 12.04,从系统发布到现在也有四年半了,其官方支持的生命周期也将止于明年春,且这在几年里出现了很多新的事物,我也需要跟 ...

  2. UNIX / Linux: 2 Ways to Add Swap Space Using dd, mkswap and swapon

    UNIX / Linux: 2 Ways to Add Swap Space Using dd, mkswap and swapon by RAMESH NATARAJAN on AUGUST 18, ...

  3. Ubuntu 添加删除用户 How to Add and Delete Users on Ubuntu 16.04

      Introduction One of the most basic tasks that you should know how to do on a fresh Linux server is ...

  4. win7 下安装 ubuntu 16.04双系统

    Ubuntu 每年发布两个版本,目前最新正式版版本也升到了 16.04.Ubuntu 16.04 开发代号为"Xenial Xerus",为第六个长期支持(LTS)版本,其主要特色 ...

  5. Ubuntu 16.04 + CUDA 8.0 + cuDNN v5.1 + TensorFlow(GPU support)安装配置详解

    随着图像识别和深度学习领域的迅猛发展,GPU时代即将来临.由于GPU处理深度学习算法的高效性,使得配置一台搭载有GPU的服务器变得尤为必要. 本文主要介绍在Ubuntu 16.04环境下如何配置Ten ...

  6. 记录2-在mac上安装ubuntu 16.04 LTS

    前几天升级了我用了六七年mac硬件,内存由4G变为8G,硬盘也换成1T SSD,索性把一直想装的ubuntu也装了,方便温习下以前的工作环境. 我比较喜欢LTS的版本,所以安装了16.04. 主要步骤 ...

  7. vsftpd for Anonymous Downloads on Ubuntu 16.04

    Introduction FTP, short for File Transfer Protocol, is a network protocol that was once widely used ...

  8. How To Move a MySQL Data Directory to a New Location on Ubuntu 16.04

    16 How To Move a MySQL Data Directory to a New Location on Ubuntu 16.04 PostedJuly 21, 2016 62.1kvie ...

  9. How To Install Nginx on Ubuntu 16.04 zz

    Introduction Nginx is one of the most popular web servers in the world and is responsible for hostin ...

随机推荐

  1. 2019-CCPC广东省赛总结

    2018年11月第一次参加ICPC区域赛青岛赛区,打铁了! 2019年5月第一次参加CCPC广东省赛,4题滚粗,C题莫队TLE13发,只拿了个铜牌! 教训总结: 比赛时千万不能犹豫,不能犹豫,不能犹豫 ...

  2. Net Core下通过Proxy 模式

    Net Core下通过Proxy 模式 NET Core下的WCF客户端也是开源的,这次发布.NET Core 2.0,同时也发布了 WCF for .NET Core 2.0.0, 本文介绍在.NE ...

  3. html select change事件触发

    做小组内使用的一个简单工具,其中要实现的一个小功能是当某个下拉菜单的选择值改变时触发另一表单元素的属性变化.自然的想到使用select表单元素的onchange事件. 下拉菜单部分的代码如下: < ...

  4. HangFire 定时任务

    https://www.cnblogs.com/ecin/p/6201262.html#%E5%9F%BA%E4%BA%8E%E9%98%9F%E5%88%97%E7%9A%84%E4%BB%BB%E ...

  5. nodejs 实践:express 最佳实践(五) connect解析

    nodejs 实践:express 最佳实践(五) connect解析 nodejs 发展很快,从 npm 上面的包托管数量就可以看出来.不过从另一方面来看,也是反映了 nodejs 的基础不稳固,需 ...

  6. VS2012快捷键消失

    我也是网上搜的不过我认为挺有效就自己摘录下来了,具体原作者也找不到,所以就下手了,望原谅. 开始菜单 -->所有程序-->Visual Studio 2012文件夹 --> Visu ...

  7. 【Java】 Maven多模块项目上传到Sonar扫描问题合集

    上传到Soanr时,项目有单元测试数,但是覆盖率为0 修改pom.xml <plugin> <groupId>org.apache.maven.plugins</grou ...

  8. [拾零]C/C++_代码复用的实现_静态链接库_动态链接库_使用.def导出

    1 静态链接库 1.1 创建静态链接库: 1.在VC6中创建项目:Win32 Static Library 2.在项目中创建两个文件:xxx.h 和 xxx.cpp 3.编译 1.2 使用静态链接库 ...

  9. Jquery 日期差函数 修改 对火狐进行兼容

    function DateDiff(sDate1, sDate2) { //sDate1和sDate2是yyyy-MM-dd格式 var aDate, oDate1, oDate2, iDays; a ...

  10. centos7使用yum安装不了ffmpeg

    [root@localhost]# yum install ffmpeg Loaded plugins: fastestmirror Loading mirror speeds from cached ...