Tutorial

How To Add Swap on Ubuntu 14.04

How To Add Swap on Ubuntu 14.04
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

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 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 space on the hard drive will be used mainly when space in RAM is no longer sufficient for data.

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’s RAM is depleted is a good safety net.

In this guide, we’ll cover how to create and enable a swap file on an Ubuntu 14.04 server.

Note

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.

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.

Check the System for Swap Information

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.

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

sudo swapon -s

Filename				Type		Size	Used	Priority

If you only get back the header of the table, as I’ve shown above, you do not currently have any swap space enabled.

Another, more familiar way of checking for swap space is with the free utility, which shows us system memory usage. We can see our current memory and swap usage in Megabytes by typing:

<pre> free -m </pre> <pre> total used free shared buffers cached Mem: 3953 154 3799 0 8 83 -/+ buffers/cache: 62 3890 <span class=“highlight”>Swap: 0</span> 0 0 </pre>

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

Check Available Space on the Hard Drive Partition

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.

Before we do this, we should be aware of our current disk usage. We can get this information by typing:

<pre> df -h </pre> <pre> Filesystem Size Used Avail Use% Mounted on <span class=“highlight”>/dev/vda 59G 1.3G 55G 3% /</span> 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 </pre>

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.

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.

Since my system has 4 Gigabytes of RAM, and doubling that would take a significant chunk of my disk space that I’m not willing to part with, I will create a swap space of 4 Gigabytes to match my system’s RAM.

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 called swapfile 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:

The Traditional, Slow Way

Traditionally, we would create a file with preallocated space by using the dd command. This versatile disk utility writes from one location to another location.

We can use this to write zeros to the file from a special device in Linux systems located at /dev/zero that just spits out as many zeros as requested.

We specify the file size by using a combination of bs for block size and count 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.

For instance, in our example, we’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:

sudo dd if=/dev/zero of=/swapfile bs=1G count=4

4+0 records in
4+0 records out
4294967296 bytes (4.3 GB) copied, 18.6227 s, 231 MB/s

Check your command before pressing ENTER because this has the potential to destroy data if you point the of (which stands for output file) to the wrong location.

We can see that 4 Gigabytes have been allocated by typing:

<pre> ls -lh /swapfile </pre> <pre> -rw-r–r-- 1 root root <span class=“highlight”>4.0G</span> Apr 28 17:15 /swapfile </pre>

If you’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.

If you want to learn how to create the file faster, remove the file and follow along below:

sudo rm /swapfile

The Faster Way

The quicker way of getting the same file is by using the fallocate program. This command creates a file of a preallocated size instantly, without actually having to write dummy contents.

We can create a 4 Gigabyte file by typing:

sudo fallocate -l 4G /swapfile

The prompt will be returned to you almost immediately. We can verify that the correct amount of space was reserved by typing:

<pre> ls -lh /swapfile </pre> <pre> -rw-r–r-- 1 root root <span class=“highlight”>4.0G</span> Apr 28 17:19 /swapfile </pre>

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

Enabling the Swap File

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.

Before we do that though, we need to adjust the permissions on our file so that it isn’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:

sudo chmod 600 /swapfile

Verify that the file has the correct permissions by typing:

<pre> ls -lh /swapfile </pre> <pre> <span class=“highlight”>-rw-------</span> 1 root root 4.0G Apr 28 17:19 /swapfile </pre>

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

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

sudo mkswap /swapfile

Setting up swapspace version 1, size = 4194300 KiB
no label, UUID=e2f1e9cf-c0a9-4ed4-b8ab-714b8a7d6944

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

sudo swapon /swapfile

We can verify that the procedure was successful by checking whether our system reports swap space now:

<pre> sudo swapon -s </pre> <pre> Filename Type Size Used Priority <span class=“highlight”>/swapfile file 4194300 0 -1</span> </pre>

We have a new swap file here. We can use the free utility again to corroborate our findings:

<pre> free -m </pre> <pre> total used free shared buffers cached Mem: 3953 101 3851 0 5 30 -/+ buffers/cache: 66 3887 <span class=“highlight”>Swap: 4095</span> 0 4095 </pre>

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

Make the Swap File Permanent

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 fstab file.

Edit the file with root privileges in your text editor:

sudo nano /etc/fstab

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:

/swapfile   none    swap    sw    0   0

Save and close the file when you are finished.

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.

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

60

For a Desktop, a swappiness setting of 60 is not a bad value. For a VPS system, we’d probably 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

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:

vm.swappiness=10

Save and close the file when you are finished.

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

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

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:

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

<div class=“author”>By Justin Ellingwood</div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
89 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

You’re missing a ‘p’ in this line:

sudo sysctl vm.swapiness=10

should be:

sudo sysctl vm.swappiness=10

I also noticed your fstab has ‘defaults’ under options, it should be ‘sw’ instead. It is the default debian/ubuntu option for swap. ‘defaults’ is a great option for your userspace filesystem, but not ideal for swap.

/swapfile none swap sw 0 0

Justin Ellingwood
DigitalOcean Employee
DigitalOcean Employee badge
May 1, 2014

Hi Brandon:

You’re absolutely right on both points. Those were oversights on my part. I’ve updated the article to reflect your suggestions.

how much swap should we create for a 1gb ram droplet? (size of swap file)

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
May 5, 2014

@chris: A general rule of thumb that people use is to have twice your memory in swap. So if you have 1 GB of RAM, you want 2 GB of swap. Though that was from back in the day when people didn’t have nearly as much memory as they usually do now. So 2 GB of swap is probably more than enough. If disk space is a concern, you can easily get away with 1 GB.

@asb then, what will we do if swap full?

Nice article Justin. Is it absolutely necessary to have some swap (at least to begin with) when upgrading memory? If I have applications that mandate not to use swap. I set the swapiness to 0 on CentOS.

You’ve still got an error in the command:

sudo sysctl vm.swapiness=10

Should have another ‘p’:

sudo sysctl vm.swappiness=10

Helpful article. Thanks.

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
June 17, 2014

@scott: Very cool! Thanks for sharing that.

Swap memory should appear on Virtualmin System information page as Virtual memory ?

Thank you very much.

“For a VPS, a swappiness setting of 60 is not a bad value. For a desktop system, we’d probably want to move it closer to 0.” So why are we changing it to 10? :P

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 8, 2014

@domwatson: It should be the other way, I’ll fix it. Thanks!

Is there any difference performance between:

sudo dd if=/dev/zero of=/swapfile bs=1G count=4

and

sudo dd if=/dev/zero of=/swapfile bs=1024 count=4G

what would you suggest?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 30, 2014

@siprof: No, the resulting files are exactly the same in both commands.

I’ve made a small script over at https://github.com/CraftThatBlock/SwapUbuntu to make this easier and faster to set all of this up

Wish I read your comment before going through it. Thanks for sharing the script, will make sure to use it next time :)

Thanks. Your script saved me.

Amazing script! And awesome article. I’ll make sure to leave feedback to see if this fixes my Wordpress issue running on ubuntu.

hi @craftthatblock i would love to try your script, but its Error 404 :(

I fixed it, thanks for notifying me!

All is work thank you

Awesome tutorial! Easy to setup everything!!!

Now just one question just to check if I got it right. Swap file/memory will be used only when free RAM falls down to 15(%)?

Great tutorial! And how do you increase swap size? Let’s say my current swap is 1GB but then I increase my droplet size so I want the swap to increase to 2GB. How do I remove the current swap and start over with 2GB? Or is there a better alternative way to make this happen?

MySQL was crashing on my 512MB droplet so I followed this guide hoping for a fix. Now my droplet is very slow, and my site won’t even load? :(

I remember your post from forum…

I guess you had a lot larger swap if not mistaken !!!

hunky yup, but all has been good a fair while now. :)

Great to know… Cheers…

This comment has been deleted

    From the Ubuntu official tutorial: https://help.ubuntu.com/community/SwapFaq

    The “diminishing returns” means that if you need more swap space than twice your RAM size, you’d better add more RAM as Hard Disk Drive (HDD) access is about 10³ slower then RAM access, so something that would take 1 second, suddenly takes more then 15 minutes! And still more then a minute on a fast Solid State Drive (SSD)…

    Thanks for this great tout. I did it as your guide and make a swap file. Is there anyway to use swap file to hibernating? You know I did not make a swap partition during the installation of ubuntu 14.04.

    Thanks for this Article. I am having 1 GB RAM. After installing Ubuntu 14.04, the OS hangs out after few minutes of usage due to deficiency of RAM. I followed the above method. Now It’s All Right… Once Again… Thanks.

    Thanks for the tutorial… Used it and found helpful… !!

    Though I would suggest people not to have such high Swap for production server !!!

    Many Linux service and programs are not swap happy I found… 1GB or MAX 2GB Swap !!!

    I have a suggestion for a neater way (IMO) of configuring the VM subsystem variables to persist after rebooting.

    In addition to the /etc/sysctl.conf configuration file mentioned in the tutorial, all files in the directory /etc/sysctl.d are parsed in sequence. The files in this directory can be used to set system, package and user-defined variables; each typically covers a quite specific subsystem, containing only one or two parameters (have a look at the existing files in the directory and you’ll see what I mean). [1]

    My suggestion is to place the new VM settings in this directory, with the benefits being that, as well as the original configuration file remaining intact, the new settings are less likely to be affected by system upgrades. Also, reverting to the default settings should simply a matter of deleting the files.

    More information is available in /etc/sysctl.d/README, which I’ve quoted here because it succinctly explains the expected file naming scheme:

    This directory contains settings similar to those found in /etc/sysctl.conf.
    In general, files in the 10-*.conf range come from the procps package and
    serve as system defaults.  Other packages install their files in the
    30-*.conf range, to override system defaults.  End-users can use 60-*.conf
    and above, or use /etc/sysctl.conf directly, which overrides anything in
    this directory.
    

    Based on this scheme, the file for configuring swappiness could be called /etc/sysctl.d/60-vm-swappiness.conf. Its contents should simply be the single configuration line described in the tutorial (comments explaining the new setting are always a good idea though):

    # Custom swappiness setting as recommended in DO tutorial:
    # https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04
    vm.swappiness=10
    

    Hopefully you get the idea and can extend this to the vfs_cache_pressure setting.

    As hinted in the README, it is not necessary to use this technique—editing the main config file will work perfectly well for end-user settings—however, some may agree with me that this is a cleaner approach.

    Cheers, John

    [1] This mechanism reminds me of some used by other Debian/Ubuntu packages, such as the apache2 package, where config files in /etc/apache2/mods-enabled and /etc/apache2/sites-enabled are parsed as part of the processing of the overall Apache config.

    Holy cow. This one is super helpful. Thank you for this!

    Concise and straight to the point, thank you very much.

    Thank you so much. All working well.

    Regards, Iyan Riana

    thank you very mush.all right.

    Fantastic tutorial. Everything worked. I’m using Digital Oceans’s WordPress with Ubuntu 14 image. My WordPress was frequently displaying “Error establishing database connection” that so often plagues new WordPress installs. I read in another Digital Ocean comment section that this would alleviate this problem. I hope so. Anyway, good to have some swap anyway. Cheers.

    I followed this and I’m still catching a “Dev/mapper/ubuntu/–vg_swap1 is not ready or is not found” upon start up. Could I be missing something or am I in the wrong place?

    I used this method, but my swap is not being used still… I have a 8GB ram but I created a 10GB ram to make it available for hibernation but when I do it says swapheader not found

    Well written article. Solved my issue. Thanks!

    Faster Way Worked perfectly (y)

    many thanks

    I have finished all steps you gave, now I think I can use the swapfile, however I got a confusion about my system, I build a swap partition when I installed the Ubuntu 14.04, I don’t know why my system shows me “zero infor.” (like your example in the beginning of this article) after I performanced the code free -m,

    run sudo vi /etc/fastab the last parts of the info. are:

     #Entry for /dev/mapper/cryptswap1 :
      UUID=bc21c3cf-2322-4663-8619-d02f255f5fbf       none    swap    sw      0       0
    
     #UUID=d3f186a3-182f-461j-9da4-bc89k0ab07fd      none    swap    sw      0       0
      /swapfile       none    swap    sw      0       0
    

    Its last line is following a step of this article, my confusion is the above of it, what does it mean? should I concern or deal with that?

    Thank you for your suggestions.

    TL;DR;

    sudo swapon -s
    free -m
    df -h
    sudo fallocate -l 4G /swapfile
    ls -lh /swapfile
    sudo chmod 600 /swapfile
    ls -lh /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    sudo swapon -s
    free -m
    

    To make the swap permanent, run:

    sudo echo "/swapfile   none    swap    sw    0   0" >> /etc/fstab
    

    Available at: https://gist.github.com/rchrd2/f13bf3f30857d9778512

    Wow! Thank you! DigitalOcean engineers always produce high-quality tutorials! Thanks for the great work! :)

    This comment has been deleted

      Hi guys, I did everything like tutorial says, but mysql stil dies and swap is not used, always is 0 in use. Can you please help me?

      Another well written tutorial by Justin…thanks a lot!

      what password i should use? not working

      root@localhost:~# swapon /swapfile swapon: /swapfile: swapon failed: Operation not permitted

      is it possible that swap creation is not allowed in VPS? any suggestions? Thank you

      Very much informative and helpful. Thank you.

      The command

      sudo dd if=/dev/zero of=/swapfile bs=1G count=4

      itself fails on a 512MB VM (“dd: memory exhausted by input buffer of size 1073741824 bytes (1.0 GiB)”). Might be nice to modify that part of the tutorial to make it small VM friendly :)

      Great tutorial! Just what I needed…thank you for the well written and thorough document!

      Hi, My host total memory is 490 mb, used=482, free=7, i set vm.swappiness = 10, total swap is 1023 , but i not see swap used ? it is 0, can you help me ?

      I am getting “dd: memory exhausted by input buffer of size 536870912 bytes (512 MiB)” This was working on your droplets before. What did you change?

      Kamal Nasser
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 29, 2015

      What exact command are you running? Try lowering the bs parameter’s value and adjusting the count value accordingly.

      For example, to create a 512MB swap file, instead of running:

      sudo dd if=/dev/zero of=/swapfile bs=512M count=1
      

      Run:

      sudo dd if=/dev/zero of=/swapfile bs=4M count=128
      

      Well written. Concise and very helpful, thanks!

      Would love to a see a feature enhancement where we can define swap while creating a droplet. Seems like an easy thing to overlook.

      I want to configure swap with 2GB, but when I put the command:

      sudo dd if=/dev/zero of=/swapfile bs=2G count=1
      

      Me returns the error:

      dd: memory exhausted by input buffer of size 2147483648 bytes (2.0 GiB)
      

      I’m using a Droplet with 1GB of RAM. Can someone help me?

      Justin Ellingwood
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 1, 2015

      @novaimprensa: Try following the suggestion laid out in this comment.

      This comment has been deleted

        How to increase swap file size ?

        It should be dd if=/dev/zero of=/swapfile bs=1024 count=1048576 otherwise it gives an error on Ubuntu

        For some reason the swap wouldn’t work until I reboot. After I did the mkswap command, the swapon -s command still showed no swap. I followed the rest of the set up, and then reboot the server before it showed any swap setup.

        Thanks man! love it!

        I followed this steps, and the commands return the expected, Swap exists, but is never used:

        top - 15:23:58 up 24 min, 1 user, load average: 0.00, 0.01, 0.04 Tasks: 81 total, 1 running, 80 sleeping, 0 stopped, 0 zombie %Cpu(s): 0.0 us, 0.3 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem: 1017928 total, 356124 used, 661804 free, 23352 buffers KiB Swap: 2023996 total, 0 used, 2023996 free. 149788 cached Mem

        Any idea why?

        This guide solved my sql server problem which stops every time due to over load. Added swap 6 hours back, didn’t stopped so far ! Thankful to you !

        Thanks, this is a truly excellent tutorial. Appreciate how you made an effort to present multiple options for many of these steps.

        Hello! I use Digital Ocean and Sentora Panel, follow the tutorial exactly as described and then restarted the server. Then when he came back I was unable to access more nehum site.

        All give this error:

        Forbidden

        You do not have permission to access / on this server.

        Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

        Apache Server at Port 80 www.cleidsmartins.com.br

        I did not do anything different, I’m for hours trying to fix it.

        if [ -f /swapfile ]; then
        	echo "The Swap file already exists."
        else
        	sudo fallocate -l 4G /swapfile
        	sudo chmod 600 /swapfile
        	sudo mkswap /swapfile
        	sudo swapon /swapfile
        	echo "/swapfile   none    swap    sw    0   0" >> /etc/fstab
        	echo "vm.swappiness = 10" >> /etc/sysctl.conf # 60 for desktops, closer to 0 for VPS
        	echo "vm.vfs_cache_pressure = 50" >> /etc/sysctl.conf
        	echo "The Swap file is created and added to '/etc/fstab' to make the changes permanent."
        fi
        

        The first example of the swapon command is wrong, the “-S” flag should be lowercase.

        Thank You. Wonderful concise cut-n-paste tutorial. I think it fixed my crashing mysql on an Amazon micro.

        For some reason I can’t add the swapfile. Is there a solution to this?

        sudo swapon /swapfile
        swapon: /swapfile: swapon failed: Operation not permitted
        

        In what scenario you would create a swap after you installed the Ubuntu? I have a swap as I installed it… what is the point unless you are upgrading with more RAM? Thanks.

        This is the first tutorial that I’ve been able to action and understand. Thank you so much; I’m hoping this will resolve some of the issues I’ve been seeing!

        Summary:

        #!/bin/bash
        # Add Swap Memory
        echo "############## SWAP ADD ##############"
        
        echo "Today's date is:"
        date +"%A, %B %-d, %Y"
        
        echo "Create a 4 Gigabyte"
        sudo fallocate -l 4G /swapfile
        
        echo "Reserved Space"
        ls -lh /swapfile
        
        echo "Permission Set - chmod 600"
        sudo chmod 600 /swapfile
        
        echo "New permission of file"
        ls -lh /swapfile
        
        echo "Tell our system to set up the swap space"
        sudo mkswap /swapfile
        
        echo "Enabling swap space...."
        sudo swapon /swapfile
        
        echo "Verify swap on procedure"
        sudo swapon -s
        
        echo "Check Memory Settings"
        free -m
        
        echo "Make Swap Permanent"
        sudo sed '$ a /swapfile   none    swap    sw    0   0' /etc/fstab
        
        SWAPINESS=`cat /proc/sys/vm/swappiness`
        
        echo "Swapiness value to 10"
        if [ "$SWAPINESS" -eq 60 ]; then
        	sudo sysctl vm.swappiness=10
          sudo sed '$ a vm.swappiness=10' /etc/sysctl.conf
        fi
        
        CACHEPRESSURE=`cat /proc/sys/vm/vfs_cache_pressure`
        
        echo "Cachepressue value to 50"
        if [ "$CACHEPRESSURE" -eq 100 ]; then
          sudo sysctl vm.vfs_cache_pressure=50
          sudo sed '$ a vm.vfs_cache_pressure = 50' /etc/sysctl.conf
        fi
        
        echo "############ SWAP ADD  END ############"
        

        Will post repo later, will end up modifying the values into variables for submission.

        Hi Justin Ellingwood

        Thank you for your article previously my server having many problems because Ram taking full memory then i increase the ram size then also note ready after that i increase the SWAP memory it will work fine

        The command:

        dd if=/dev/zero of=/swapfile bs=1G count=4
        

        gave me this error: “dd: memory exhausted by input buffer of size 1073741824 bytes (1.0 GiB)”. So I used this command instead, which did the exact same thing, and everything worked just fine on Ubuntu 14.04:

        dd if=/dev/zero of=/swapfile bs=1M count=4000
        

        Is there a way to change the swat file size fast? And if i want to change it, by deleting it and/or recreating it, will i run into problems if i just delete it or overwrite it?

        This comment has been deleted

          Tired of doing this for every single Droplet?

          Here’s a script: https://github.com/budhajeewa/ubuntu-create-swap/blob/master/ubuntu-create-swap.sh

          I’ve only copied and pasted steps from here.

          Helpful article. Thanks.

          Excellent and very objective tutorial.

          I tried this out on 3 Debian Jessie Droplets and several Ubuntu 16.04. The commands are valid for both and made a big difference to performance. Thanks!

          Hello guys, I did all steps carefully but I think my server not working in this case.

          My server status after run this: free -m

          Mem: 3953 3114 838 64 434 537 Swap: 4095 0 4095

          http://www.awesomescreenshot.com/showImage?img_id=1290414

          Used memory showing Zero value. I am confused, please advice me.

          Thank you.

          Just in case someone wonders… I needed to finish the tutorial even though when I ran sudo swapon -s it did not show a swapfile being used. I made the swap file permanent then shutdown/rebooted the vps. Only then did sudo swapon -s work. Just in case.

          I’ve deployed the Discourse to the $5 Droplet and whenever I’ve been resizing RAM by the using SWAP it’s getting to be disappeared after rebooting the Droplet. Previously, the SWAP worked almost during a week, when I checked it some several times. Does someone was experienced with this issue?

          root@discourse:/var/discourse# free -m
                       total       used       free     shared    buffers     cached
          Mem:           489        483          6         36          0         39
          -/+ buffers/cache:        443         46
          Swap:            0          0          0
          root@discourse:/var/discourse# sudo swapon -s
          Filename                Type        Size    Used    Priority
          root@discourse:/var/discourse# free -m
                       total       used       free     shared    buffers     cached
          Mem:           489        484          5         36          3         53
          -/+ buffers/cache:        426         63
          Swap:            0          0          0
          root@discourse:/var/discourse# df -h
          Filesystem      Size  Used Avail Use% Mounted on
          udev            235M  4.0K  235M   1% /dev
          tmpfs            49M  408K   49M   1% /run
          /dev/vda1        20G  6.4G   13G  34% /
          none            4.0K     0  4.0K   0% /sys/fs/cgroup
          none            5.0M     0  5.0M   0% /run/lock
          none            245M  632K  245M   1% /run/shm
          none            100M     0  100M   0% /run/user
          none             20G  6.4G   13G  34% /var/lib/docker/aufs/mnt/2bafc4dd7a99c9b40bd5f0bb0e68408c975a6142c3414305ffb4768e491e314a
          shm              64M  4.0K   64M   1% /var/lib/docker/containers/939ac5af77d2692d006f9c8f51a1dd590a0e1254d9159a38c4ed0986ea717f39/shm
          root@discourse:/var/discourse# sudo dd if=/dev/zero of=/swapfile bs=1G count=1
          dd: memory exhausted by input buffer of size 1073741824 bytes (1.0 GiB)
          root@discourse:/var/discourse# ls -lh /swapfile
          -rw------- 1 root root 0 Jun 22 22:28 /swapfile
          root@discourse:/var/discourse# sudo fallocate -l 1G /swapfile
          root@discourse:/var/discourse# ls -lh /swapfile
          -rw-r--r-- 1 root root 1.0G Jun 22 22:30 /swapfile
          root@discourse:/var/discourse# sudo chmod 600 /swapfile
          root@discourse:/var/discourse# ls -lh /swapfile
          -rw------- 1 root root 1.0G Jun 22 22:30 /swapfile
          root@discourse:/var/discourse# sudo mkswap /swapfile
          Setting up swapspace version 1, size = 1048572 KiB
          no label, UUID=13d8d52f-1f90-4f6a-8de1-89b93ae553cb
          root@discourse:/var/discourse# sudo swapon /swapfile
          root@discourse:/var/discourse# sudo swapon -s
          Filename                Type        Size    Used    Priority
          /swapfile                               file        1048572 0   -1
          root@discourse:/var/discourse# free -m
                       total       used       free     shared    buffers     cached
          Mem:           489        483          6         36          8         74
          -/+ buffers/cache:        399         90
          Swap:         1023          0       1023
          root@discourse:/var/discourse# sudo nano /etc/fstab
          Use "fg" to return to nano.
          
          [1]+  Stopped                 sudo nano /etc/fstab
          root@discourse:/var/discourse# cat /proc/sys/vm/swappiness
          60
          root@discourse:/var/discourse# sudo sysctl vm.swappiness=10
          vm.swappiness = 10
          root@discourse:/var/discourse# sudo nano /etc/sysctl.conf
          root@discourse:/var/discourse# cat /proc/sys/vm/vfs_cache_pressure
          100
          root@discourse:/var/discourse# sudo sysctl vm.vfs_cache_pressure=50
          vm.vfs_cache_pressure = 50
          root@discourse:/var/discourse# sudo nano /etc/sysctl.conf
          root@discourse:/var/discourse# cd
          root@discourse:~# reboot
          root@discourse:~#
          Broadcast message from itamerlanium@discourse
              (/dev/pts/0) at 22:35 ...
          
          The system is going down for reboot NOW!
          Connection to 159.203.205.195 closed by remote host.
          Connection to 159.203.205.195 closed.
          MacBook-Air-3:~ macbookair$ ssh itamerlanium@159.203.205.195
          itamerlanium@159.203.205.195's password:
          Welcome to Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-85-generic x86_64)
          
           * Documentation:  https://help.ubuntu.com/
          
            System information as of Wed Jun 22 22:36:01 EDT 2016
          
            System load: 0.0                Memory usage: 10%   Processes:       54
            Usage of /:  37.3% of 19.56GB   Swap usage:   0%    Users logged in: 0
          
            Graph this data and manage this system at:
              https://landscape.canonical.com/
          
          Last login: Wed Jun 22 22:02:25 2016 from 103.250.119.238
          itamerlanium@discourse:~$ sudo su
          [sudo] password for itamerlanium:
          root@discourse:/home/itamerlanium# cd
          root@discourse:~# cd /var/discourse/
          root@discourse:/var/discourse# free -m
                       total       used       free     shared    buffers     cached
          Mem:           489        484          5         34          2         50
          -/+ buffers/cache:        431         58
          Swap:            0          0          0
          root@discourse:/var/discourse#
          

          Thanks!

          This just made my day. Thank you for being so competent

          Great article. Solved my problem. Thanks!

          God bless you

          fallocate: /swapfile: fallocate failed: Text file busy

          Hey,

          great tutorial, thanks. What’s with the note at the beginning saying it is not recommended to use swap when having a droplet with a ssd. I’m running out of RAM when installing all my npm modules, however, for the project running my RAM capacity is fine. Can I keep using swap (I used this solution for other projects as well) or are there alternative solutions ( other than just upgrading my droplet)?

          Cheers

          it worked for me

          You are really making this world a better place!

          Thank you very much!

          Brilliant post, very complete and tested. Kindly append steps to increase swap file size.

          Thanks

          Great Article !!

          This comment has been deleted

            Awesome, thanks so much!

            alt text
            Thumbs Up

            Hey, that was great documentation and helpful, but this doc has some raw HTML code <pre>, etc. Can you please edit the docs correctly and update them? So it will be easy to look into the expected outputs.

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Become a contributor for community

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            DigitalOcean Documentation

            Full documentation for every DigitalOcean product.

            Resources for startups and SMBs

            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

            Get our newsletter

            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

            New accounts only. By submitting your email you agree to our Privacy Policy

            The developer cloud

            Scale up as you grow — whether you're running one virtual machine or ten thousand.

            Get started for free

            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

            *This promotional offer applies to new accounts only.