{"id":5717,"date":"2016-06-21T09:24:05","date_gmt":"2016-06-21T06:24:05","guid":{"rendered":"http:\/\/www.karadere.com\/blog\/?p=5717"},"modified":"2016-06-21T10:29:17","modified_gmt":"2016-06-21T07:29:17","slug":"how-to-add-swap-on-ubuntu-14-04","status":"publish","type":"post","link":"https:\/\/www.karadere.com\/blog\/how-to-add-swap-on-ubuntu-14-04.html","title":{"rendered":"How To Add Swap on Ubuntu 14.04"},"content":{"rendered":"<h1 class=\"content-title\">How To Add Swap on Ubuntu 14.040<\/h1>\n<figure style=\"width: 300px\" class=\"wp-caption alignleft\"><img loading=\"lazy\" decoding=\"async\" class=\"\" src=\"http:\/\/techandroot.com\/wp-content\/uploads\/2014\/12\/UBN00216-11-300x300.jpg\" width=\"300\" height=\"300\" \/><figcaption class=\"wp-caption-text\">Ubuntu 14.04<\/figcaption><\/figure>\n<h3 id=\"introduction\">Introduction<\/h3>\n<p>One of the easiest way of increasing the responsiveness of your server and guarding against out of memory errors in your applications is to add some swap space. <strong>Swap<\/strong> 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.<\/p>\n<p>Basically, this gives you the ability to increase the amount of information that your server can keep in its working &#8220;memory&#8221;, with some caveats. The space on the hard drive will be used mainly when space in RAM is no longer sufficient for data.<\/p>\n<p>The information written to disk will be 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&#8217;s RAM is depleted is a good safety net.<\/p>\n<p>In this guide, we&#8217;ll cover how to create and enable a swap file on an Ubuntu 14.04 server.<\/p>\n<div class=\"code-label notes-and-warnings note\" title=\"Note\">Note<\/div>\n<p>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.<\/p>\n<p>If you need to improve the performance of your server, 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.<\/p>\n<div data-unique=\"check-the-system-for-swap-information\"><\/div>\n<h2 id=\"check-the-system-for-swap-information\">Check the System for Swap Information<\/h2>\n<p>Before we begin, we will take a look at our operating system to see if we already have some swap space available. We can have multiple swap files or swap partitions, but generally one should be enough.<\/p>\n<p>We can see if the system has any configured swap by typing:<\/p>\n<pre class=\"code-pre \"><code>sudo swapon -s\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>Filename                Type        Size    Used    Priority\r\n<\/code><\/pre>\n<p>If you only get back the header of the table, as I&#8217;ve shown above, you do not currently have any swap space enabled.<\/p>\n<p>Another, more familiar way of checking for swap space is with the <code>free<\/code> utility, which shows us system memory usage. We can see our current memory and swap usage in Megabytes by typing:<\/p>\n<pre>free -m\r\n<\/pre>\n<pre>             total       used       free     shared    buffers     cached\r\nMem:          3953        154       3799          0          8         83\r\n-\/+ buffers\/cache:         62       3890\r\n<span class=\"highlight\">Swap:            0<\/span>          0          0\r\n<\/pre>\n<p>As you can see above, our total swap space in the system is &#8220;0&#8221;. This matches what we saw with the previous command.<\/p>\n<div data-unique=\"check-available-space-on-the-hard-drive-partition\"><\/div>\n<h2 id=\"check-available-space-on-the-hard-drive-partition\">Check Available Space on the Hard Drive Partition<\/h2>\n<p>The typical 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.<\/p>\n<p>Before we do this, we should be aware of our current disk usage. We can get this information by typing:<\/p>\n<pre>df -h\r\n<\/pre>\n<pre>Filesystem      Size  Used Avail Use% Mounted on\r\n<span class=\"highlight\">\/dev\/vda         59G  1.3G   55G   3% \/<\/span>\r\nnone            4.0K     0  4.0K   0% \/sys\/fs\/cgroup\r\nudev            2.0G   12K  2.0G   1% \/dev\r\ntmpfs           396M  312K  396M   1% \/run\r\nnone            5.0M     0  5.0M   0% \/run\/lock\r\nnone            2.0G     0  2.0G   0% \/run\/shm\r\nnone            100M     0  100M   0% \/run\/user\r\n<\/pre>\n<p>As you can see on the first line, our hard drive partition has 55 Gigabytes available, so we have a huge amount of space to work with. This is on a fresh, medium-sized VPS instance, however, so your actual usage might be very different.<\/p>\n<p>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.<\/p>\n<p>Since my system has 4 Gigabytes of RAM, and doubling that would take a significant chunk of my disk space that I&#8217;m not willing to part with, I will create a swap space of 4 Gigabytes to match my system&#8217;s RAM.<\/p>\n<div data-unique=\"create-a-swap-file\"><\/div>\n<h2 id=\"create-a-swap-file\">Create a Swap File<\/h2>\n<p>Now that we know our available hard drive space, we can go about creating a swap file within our filesystem.<\/p>\n<p>We will create a file called <code>swapfile<\/code> in our root (\/) directory. The file must allocate the amount of space we want for our swap file. There are two main ways of doing this:<\/p>\n<h3 id=\"the-traditional-slow-way\">The Traditional, Slow Way<\/h3>\n<p>Traditionally, we would create a file with preallocated space by using the <code>dd<\/code> command. This versatile disk utility writes from one location to another location.<\/p>\n<p>We can use this to write zeros to the file from a special device in Linux systems located at <code>\/dev\/zero<\/code> that just spits out as many zeros as requested.<\/p>\n<p>We specify the file size by using a combination of <code>bs<\/code> for block size and <code>count<\/code> for the number of blocks. What we assign to each parameter is almost entirely arbitrary. What matters is what the product of multiplying them turns out to be.<\/p>\n<p>For instance, in our example, we&#8217;re looking to create a 4 Gigabyte file. We can do this by specifying a block size of 1 Gigabyte and a count of 4:<\/p>\n<pre class=\"code-pre \"><code>sudo dd if=\/dev\/zero of=\/swapfile bs=1G count=4\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>4+0 records in\r\n4+0 records out\r\n4294967296 bytes (4.3 GB) copied, 18.6227 s, 231 MB\/s\r\n<\/code><\/pre>\n<p>Check your command before pressing ENTER because this has the potential to destroy data if you point the <code>of<\/code> (which stands for output file) to the wrong location.<\/p>\n<p>We can see that 4 Gigabytes have been allocated by typing:<\/p>\n<pre>ls -lh \/swapfile\r\n<\/pre>\n<pre>-rw-r--r-- 1 root root <span class=\"highlight\">4.0G<\/span> Apr 28 17:15 \/swapfile\r\n<\/pre>\n<p>If you&#8217;ve completed the command above, you may notice that it took quite a while. In fact, you can see in the output that it took my system 18 seconds to create the file. That is because it has to write 4 Gigabytes of zeros to the disk.<\/p>\n<p>If you want to learn how to create the file faster, remove the file and follow along below:<\/p>\n<pre class=\"code-pre \"><code>sudo rm \/swapfile\r\n<\/code><\/pre>\n<h3 id=\"the-faster-way\">The Faster Way<\/h3>\n<p>The quicker way of getting the same file is by using the <code>fallocate<\/code> program. This command creates a file of a preallocated size instantly, without actually having to write dummy contents.<\/p>\n<p>We can create a 4 Gigabyte file by typing:<\/p>\n<pre class=\"code-pre \"><code>sudo fallocate -l 4G \/swapfile\r\n<\/code><\/pre>\n<p>The prompt will be returned to you almost immediately. We can verify that the correct amount of space was reserved by typing:<\/p>\n<pre>ls -lh \/swapfile\r\n<\/pre>\n<pre>-rw-r--r-- 1 root root <span class=\"highlight\">4.0G<\/span> Apr 28 17:19 \/swapfile\r\n<\/pre>\n<p>As you can see, our file is created with the correct amount of space set aside.<\/p>\n<div data-unique=\"enabling-the-swap-file\"><\/div>\n<h2 id=\"enabling-the-swap-file\">Enabling the Swap File<\/h2>\n<p>Right now, our file is created, but our system does not know that this is supposed to be used for swap. We need to tell our system to format this file as swap and then enable it.<\/p>\n<p>Before we do that though, we need to adjust the permissions on our file so that it isn&#8217;t readable by anyone besides root. Allowing other users to read or write to this file would be a huge security risk. We can lock down the permissions by typing:<\/p>\n<pre class=\"code-pre \"><code>sudo chmod 600 \/swapfile\r\n<\/code><\/pre>\n<p>Verify that the file has the correct permissions by typing:<\/p>\n<pre>ls -lh \/swapfile\r\n<\/pre>\n<pre><span class=\"highlight\">-rw-------<\/span> 1 root root 4.0G Apr 28 17:19 \/swapfile\r\n<\/pre>\n<p>As you can see, only the columns for the root user have the read and write flags enabled.<\/p>\n<p>Now that our file is more secure, we can tell our system to set up the swap space by typing:<\/p>\n<pre class=\"code-pre \"><code>sudo mkswap \/swapfile\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>Setting up swapspace version 1, size = 4194300 KiB\r\nno label, UUID=e2f1e9cf-c0a9-4ed4-b8ab-714b8a7d6944\r\n<\/code><\/pre>\n<p>Our file is now ready to be used as a swap space. We can enable this by typing:<\/p>\n<pre class=\"code-pre \"><code>sudo swapon \/swapfile\r\n<\/code><\/pre>\n<p>We can verify that the procedure was successful by checking whether our system reports swap space now:<\/p>\n<pre>sudo swapon -s\r\n<\/pre>\n<pre>Filename                Type        Size    Used    Priority\r\n<span class=\"highlight\">\/swapfile               file        4194300 0       -1<\/span>\r\n<\/pre>\n<p>We have a new swap file here. We can use the <code>free<\/code> utility again to corroborate our findings:<\/p>\n<pre>free -m\r\n<\/pre>\n<pre>             total       used       free     shared    buffers     cached\r\nMem:          3953        101       3851          0          5         30\r\n-\/+ buffers\/cache:         66       3887\r\n<span class=\"highlight\">Swap:         4095<\/span>          0       4095\r\n<\/pre>\n<p>Our swap has been set up successfully and our operating system will begin to use it as necessary.<\/p>\n<div data-unique=\"make-the-swap-file-permanent\"><\/div>\n<h2 id=\"make-the-swap-file-permanent\">Make the Swap File Permanent<\/h2>\n<p>We have our swap file enabled, but when we reboot, the server will not automatically enable the file. We can change that though by modifying the <code>fstab<\/code> file.<\/p>\n<p>Edit the file with root privileges in your text editor:<\/p>\n<pre class=\"code-pre \"><code>sudo nano \/etc\/fstab\r\n<\/code><\/pre>\n<p>At the bottom of the file, you need to add a line that will tell the operating system to automatically use the file you created:<\/p>\n<pre class=\"code-pre \"><code>\/swapfile   none    swap    sw    0   0\r\n<\/code><\/pre>\n<p>Save and close the file when you are finished.<\/p>\n<div data-unique=\"tweak-your-swap-settings\"><\/div>\n<h2 id=\"tweak-your-swap-settings\">Tweak your Swap Settings<\/h2>\n<p>There are a few options that you can configure that will have an impact on your system&#8217;s performance when dealing with swap.<\/p>\n<p>The <code>swappiness<\/code> 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.<\/p>\n<p>With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are &#8220;expensive&#8221; 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.<\/p>\n<p>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&#8217; memory profile or what you are using your server for, this might be better in some cases.<\/p>\n<p>We can see the current swappiness value by typing:<\/p>\n<pre class=\"code-pre \"><code>cat \/proc\/sys\/vm\/swappiness\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>60\r\n<\/code><\/pre>\n<p>For a Desktop, a swappiness setting of 60 is not a bad value. For a VPS system, we&#8217;d probably want to move it closer to 0.<\/p>\n<p>We can set the swappiness to a different value by using the <code>sysctl<\/code> command.<\/p>\n<p>For instance, to set the swappiness to 10, we could type:<\/p>\n<pre class=\"code-pre \"><code>sudo sysctl vm.swappiness=10\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>vm.swappiness = 10\r\n<\/code><\/pre>\n<p>This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our <code>\/etc\/sysctl.conf<\/code> file:<\/p>\n<pre class=\"code-pre \"><code>sudo nano \/etc\/sysctl.conf\r\n<\/code><\/pre>\n<p>At the bottom, you can add:<\/p>\n<pre class=\"code-pre \"><code>vm.swappiness=10\r\n<\/code><\/pre>\n<p>Save and close the file when you are finished.<\/p>\n<p>Another related value that you might want to modify is the <code>vfs_cache_pressure<\/code>. This setting configures how much the system will choose to cache inode and dentry information over other data.<\/p>\n<p>Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it&#8217;s an excellent thing for your system to cache. You can see the current value by querying the <code>proc<\/code> filesystem again:<\/p>\n<pre class=\"code-pre \"><code>cat \/proc\/sys\/vm\/vfs_cache_pressure\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>100\r\n<\/code><\/pre>\n<p>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:<\/p>\n<pre class=\"code-pre \"><code>sudo sysctl vm.vfs_cache_pressure=50\r\n<\/code><\/pre>\n<pre class=\"code-pre \"><code>vm.vfs_cache_pressure = 50\r\n<\/code><\/pre>\n<p>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:<\/p>\n<pre class=\"code-pre \"><code>sudo nano \/etc\/sysctl.conf\r\n<\/code><\/pre>\n<p>At the bottom, add the line that specifies your new value:<\/p>\n<pre class=\"code-pre \"><code>vm.vfs_cache_pressure = 50\r\n<\/code><\/pre>\n<p>Save and close the file when you are finished.<\/p>\n<div data-unique=\"conclusion\"><\/div>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Following the steps in this guide will give you some breathing room in terms of your RAM usage. Swap space is incredibly useful in avoiding some common problems.<\/p>\n<p>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. Configuring swap space, however, can give you more flexibility and can help buy you time on a less powerful server.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How To Add Swap on Ubuntu 14.040 Introduction One of the easiest way of increasing the responsiveness of your server and guarding against out of memory errors in your applications is to add some swap space. Swap is an area on a hard drive that has been designated as a place where the operating system [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":"","_links_to":"","_links_to_target":""},"categories":[2],"tags":[2599,2597,1127,1595,2598,2077,2120],"class_list":["post-5717","post","type-post","status-publish","format-standard","hentry","category-2015-2016","tag-14-04","tag-add","tag-how","tag-on","tag-swap","tag-to","tag-ubuntu","has-post-title","has-post-date","has-post-category","has-post-tag","has-post-comment","has-post-author",""],"aioseo_notices":[],"views":4659,"_links":{"self":[{"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/posts\/5717","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/comments?post=5717"}],"version-history":[{"count":2,"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/posts\/5717\/revisions"}],"predecessor-version":[{"id":5719,"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/posts\/5717\/revisions\/5719"}],"wp:attachment":[{"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/media?parent=5717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/categories?post=5717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.karadere.com\/blog\/wp-json\/wp\/v2\/tags?post=5717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}