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

Status: Deprecated

This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:

Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.

See Instead:
This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.

About Linux Swapping

Linux RAM is composed of chunks of memory called pages. To free up pages of RAM, a “linux swap” can occur and a page of memory is copied from the RAM to preconfigured space on the hard disk. Linux swaps allow a system to harness more memory than was originally physically available.

However, swapping does have disadvantages. Because hard disks have a much slower memory than RAM, virtual private server performance may slow down considerably. Additionally, swap thrashing can begin to take place if the system gets swamped from too many files being swapped in and out.


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 for Swap Space

Before we proceed to set up a swap file, we need to check if any swap files have been enabled on the VPS by looking at the summary of swap usage.

sudo swapon -s

An empty list will confirm that you have no swap files enabled:

Filename				Type		Size	Used	Priority

Check the File System

After we know that we do not have a swap file enabled on the virtual server, we can check how much space we have on the server with the df command. The swap file will take 256MB— since we are only using up about 8% of the /dev/sda, we can proceed.

Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda        20907056 1437188  18421292   8% /
udev              121588       4    121584   1% /dev
tmpfs              49752     208     49544   1% /run
none                5120       0      5120   0% /run/lock
none              124372       0    124372   0% /run/shm

Create and Enable the Swap File

Now it’s time to create the swap file itself using the dd command :

sudo dd if=/dev/zero of=/swapfile bs=1024 count=256k

“of=/swapfile” designates the file’s name. In this case the name is swapfile.

Subsequently we are going to prepare the swap file by creating a linux swap area:

sudo mkswap /swapfile

The results display:

Setting up swapspace version 1, size = 262140 KiB
no label, UUID=103c4545-5fc5-47f3-a8b3-dfbdb64fd7eb

Finish up by activating the swap file:

sudo swapon /swapfile

You will then be able to see the new swap file when you view the swap summary.

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

This file will last on the virtual private server until the machine reboots. You can ensure that the swap is permanent by adding it to the fstab file.

Open up the file:

sudo nano /etc/fstab

Paste in the following line:

 /swapfile       none    swap    sw      0       0 

Swappiness in the file should be set to 10. Skipping this step may cause both poor performance, whereas setting it to 10 will cause swap to act as an emergency buffer, preventing out-of-memory crashes.

You can do this with the following commands:

echo 10 | sudo tee /proc/sys/vm/swappiness
echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf

To prevent the file from being world-readable, you should set up the correct permissions on the swap file:

sudo chown root:root /swapfile 
sudo chmod 0600 /swapfile
By Etel Sverdlov


  • Thanks! But how can I test the swap effectiveness?
  • You can see the swap summary with the command "swapon -s"
  • Do we have to reboot after swapon /swapfile ?
  • no reboot is necessary after the swapon command.
  • What is the > bs=1024 count=512k < in the above command? How do we set the size? for example if I'm running on a 256mb plan C
  • BS stands for blocksize and in this case it will be 1,024 bytes. Count is how many times to write this block, or 512,000 * 1,024 bytes = 512MB of SWAP
  • Thank you guys! That's very useful!
  • Please note that for security reasons it is advisable to enter something like: # chown root:root /swapfile # chmod 0600 /swapfile source:
  • Thanks, Andrea, I have added that to the tutorial!
  • For anyone who wants to increase their swapsize after they have followed this tutorial you can follow the below steps. With the increase in memory on the base packages from 256MB to 512MB, I wanted to create a swap file double the "physical" memory size ie 1GB instead of the 512MB made in this tutorial: 1. Turn the swapfile off : swapoff -a 2. sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k 3. Follow the remaining steps from after the dd command. Except for the Fstab modification as that is already completed. 4. Your swapfile is now bigger
  • Minor suggestion is that you need sudo before those last two chown/chmod commands and I noticed the dd command took a few minutes so it would be reassuring to note this to avoid worry that something has gone wrong!
  • That's correct you will want to either use sudo or do this as root. And the dd command is writing directly to disk so it will take a bit of time depending on the size of the swapfile that is written. Thanks for pointing that out.
  • Thanks, this worked great. You can see how much swap is being used by entering top -c right below the memory usage. Have yet to see my server use the swap - but its there if it needs it and its great that DigitalOcean uses a SSD so the swap should be quicker than other hosts.
  • Is there a downside to setting the swap to be very large? I have 2GB of memory and my site takes ~100mb.. so would it be bad to have a 4GB swap?
  • Thanks for your article. My web site's db (mysql) drop 3 - 4 times, i hope it will help
  • @danafrancey The only downside is that you use more diskspace for swap, and you probably don't need to...
  • Optionally, to change the swappiness of the system, edit /etc/sysctl.conf And add a line at the bottom: vm.swappiness=20 Then type: sysctl -p This sets the system to swap memory only when RAM usage is more than 80%, default was swapping when RAM usage was more than 60%, which results in most of the services being swapped if you experience a traffic spike.
  • Tiny detail: The number 262140 found twice in the article should really be 524284 :-)
  • when can i see any memory been swapped? 30 mins after setting this and I type `free` command: total used free shared buffers cached Mem: 508396 501272 7124 0 20472 340460 -/+ buffers/cache: 140340 368056 Swap: 524284 0 524284
  • You can use fallocate instead of dd to speed up the file creation - instead of manually writing each 0 like dd does, it just makes the container of the file: # fallocate -l 512M /swapfile is equivalent to # dd if=/dev/zero of=/swapfile bs=1M count=512 and takes under a second or two to execute.
  • Great tutorial! Luckily, I stumbled onto it by accident. For the benefit of other future newbies, a link to this tutorial should be referenced in other rudimentary HowTos... just a suggestion.
  • silly but can u have more than 1 swap file? i mean.. can i have like... 5 swap files using 30% of my host space? buddy press is memory hungry :(
  • Disadvantages section : "Because hard disks have a much slower memory than RAM, virtual private server performance may slow down considerably. " But DigitalOcean uses a SSD , not hard drive. So this statement is useless. What exactly does a droplet use swap for, and how much is optimal? Thanks
  • @leo: You shouldn't have more than 1 swap file - you should instead increase the size of your swap file. @yangyun: It's not useless - even SSDs are still slower than RAM. As per the article: Linux RAM is composed of chunks of memory called pages. To free up pages of RAM, a “linux swap” can occur and a page of memory is copied from the RAM to preconfigured space on the hard disk. Linux swaps allow a system to harness more memory than was originally physically available.
  • In case of debian you might have to run the command 'swapon' with 'sudo', otherwise it might return "command not found".
  • Or use '/sbin/swapon -s' mostly because /sbin is not added to the PATH of a normal user by default.
  • @kadaj: Thanks! I've updated the article.
  • Super easy and worked perfectly. Capistrano wasn't deploying because it said I didn't have enough RAM to precompile my assets ["Rake aborted! Cannot allocate memory - nodejs ... ]. Enabled 1GB swap file. Voila, problem solved. Thanks!
  • Thanks a lot, mysql was falling down like ones a week until I discover the reason via nagios.
  • i really dont know how to do as below mention. can anyone rewrite it in more detail method? Optionally, to change the swappiness of the system, edit /etc/sysctl.conf And add a line at the bottom: vm.swappiness=20 Then type: sysctl -p This sets the system to swap memory only when RAM usage is more than 80%, default was swapping when RAM usage was more than 60%, which results in most of the services being swapped if you experience a traffic spike.
  • @nhatkhoa: This is a one-line command of the mentioned section :]
    echo "vm.swappiness=20" | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
  • Is it possible to Create LVL Partion for Snapshots same way ?
  • Does anybody else get "swapon: /swapfile: swapon failed: Device or resource busy" when following this tutorial on Ubuntu 13.04?
  • @eli.xir: Unfortunately that's not possible.
  • @gwilymgj: Does /swapfile already exist?
    stat /swapfile
  • Is there any way to have encrypted swap? The instructions I've seen includes mounting the swapfile as a loop device, which isn't supported by the vm (or so it seems).
  • I noticed when I reboot my machine (for an image creation), the swap file vanishes and I have to go through this process again. I'm fine just using a cron job to automate it, but am I doing something wrong?
  • @shade: It shouldn't just "vanish". Can you please try it on a fresh new droplet and see if you can replicate it?
  • sysctl -w vm.swappiness=0
  • Excellent article. My MySQL kept crashing due to 'out of memory' issues. Hopefully this will solve it.
  • Couldn't change swappiness with the tutorial method brian's comment above worked. sysctl -w vm.swappiness=0
  • I'm very new to this and am therefore following the instructions literally. On a fresh install dual boot with win 7 Pro x64 I've installed Ubuntu 12.04 LTS and all seems to be working. Checked that there was no swap file (cannot create a 5th partition so will be using a file). Entered the above command line sudo dd if=/dev/zero of=/swapfile bs=1024 count=8192k except made the swap file the size of the RAM. It took a bit and then returned 8388608+0 records in 8388608+0 records out 8589934592 bytes (8.6 GB) copied, 71.4647 s, 120 MB/s So far so good. I typed sudo mkswap /swapfile and the response was /swapfile: No such file or directory So I figure there is an assumption somewhere that I've missed. Any advice would be appreciated.
  • @dlingen: I don't recommend using a swapfile too large because it might actually decrease performance. 512MB is usually enough. Make sure that /swapfile exists:
    stat /swapfile
  • Same as @niusheng, I had to enable the swap before it would begin using it. `sudo swapon -a`
  • The method for setting the swappiness in the article doesn't result in the setting being preserved over a system reboot. As suggested by anonymous, I think you need to add a step editing the /etc/sysctl.conf file to a add a vm.swappiness=0 line.
  • When i run "top" command the swap used is always 0k. I installed a 512M swap as mysql on my server kept crashing and many people suggested me to do so as mysql might be running out of memory. But mysql still crashes and i dont see any sign of swap being used. Have i installed the swap correctly? or the reason for the crash may be different? thanks in advance
  • I do all step on this tutorial and create swap file Filename Type Size Used Priority /swap file 1048572 0 -1 Then I run rvmsudo passenger-install-nginx-module, but process terminate with "Your compiler failed with the exit status 4" I connect to host in second window and execute swap on -s, when I try install passenger, and see that swap Used = 0 What I did wrong? Why swap doesn't used?
  • @arunbluez: Swap not being used is usually a good sign. However, if apps still crash, there's something wrong. What's the output of sudo swapon -s?
  • @bondarenko.ik: I've never used rvmsudo, does exit status 4 mean it ran out of memory?
  • @Kamal Yeah! And i did this! I made swap with sudo but not root user, it was mistake
  • @bondarenko.ik: Hmm. Does running sysctl vm.swappiness=10 fix it?
  • I'm having the same problem as @arunbluez but I definitely have swapon set correctly: $ sudo swapon -s Filename Type Size Used Priority /swapfile file 1048572 0 -1
  • @jamesorodig: Please see my comment above (January 26th, 2014 14:11).
  • Great article, thank you :)
  • @kamal: thanks for the tut. But on a small droplet with 512M RAM, woildn't setting the swappiness to 0 cause the swap only when all RAM is used? Wouldn't it be better to, by default, do what you suggested above by setting swappiness to slightly higher than 0? Or is the swappiness predictive so that RAM is never filled before the swap kicks in?
  • I'm new to running a VPS like this and happened upon this article only because I was worried about the memory usage on my droplet (currently at 44% without anything really running on it apart from the base server setup: LEMP, php5-cli, imagick, etc). Anyway, this is really useful if it actually brings down the memory usage. I'm not sure if using all the memory is bad but I'm assuming it is. This should really be linked to from some of the basic setup articles to help people along -- seems like a necessity to have on a server.
  • I'm on a 1Gb droplet currently, should I be enabling my swap to be 2Gb (like @Rob Jatho suggests by doubling the 512Mb droplet) and if so, would i increase the BS from 1024 or just the count to 2048? Also, I read here: that if the swap file is greater than 1Gb, it makes sense to have two 1Gb files (for a 2Gb swap) instead of just one...but in the comments @Kamal Nasser suggests only using one swap with just a bigger size? Surely there are exceptions to this and it really doesn't make sense to only have a 1Gb swap on my 1Gb physical memory droplet after reading the above about doubling your memory on swap. This is all new to me though so I'm open to suggestions!
  • `vm.swappiness=0` will lead to processes being killed instead of swapped out. I'd recommend to use `10` or more.
  • Thank you that's very useful, I was wondering why the swap wasn't working.. it wasn't create
  • when I'm running 'rvmsudo passenger-install-nginx-module' i still have the same issue "need to increase my swap space" My current 'swappon -s" is Filename Type Size Used Priority /swapfile file 524284 0 -1 /swap file 1048572 0 -2
  • Thanks for sharing. But how swapped memory gets freed up?
  • Im getting an error: swapon: /swapfile: swapon failed: Operation not permitted After typing: swapon /swapfile
  • @sohara89 You need to have sudo in there so: sudo swapon /swapfile
  • Hi guys, After upgrade my droplet from 512ram to 1gb my old swap file disappeared (Maybe not but now I don't see it in webmin system information). Before upgrade I created swap file 512mb. Now I want to add new swap file, to have it just in case, because I realized that mysql server can suddenly just stop sometimes... I have two questions: 1. Is there any recommendation for swap size on ubuntu, where I have 1gb of ram memory? 2. Can I somehow check what happened with old swap file? Maybe it just wasting my space now? "sudo swapon -s" gives me empty list: Filename Type Size Used Priority Thanks!
  • I'm guessing you wanted echo 10 | sudo tee /proc/sys/vm/swappiness not 0, since the 2 lines differ?
  • @ogerpack2005: Nice catch, I completely missed that when I updated the article. I'll correct it, thanks!
  • @djolepiv: You can check if it exists by running
    stat /swapfile
  • The swap settings in the article differ and won't be preserved across reboots! echo 0 | sudo tee /proc/sys/vm/swappiness ^ this line sets the file up as an emergency out-of-memory swap, which is what it should be on a server. echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf ^ this one is what will be activated across reboots and may cause swapping even though the server isn't completely out of memory. Change the 10 in the second line to a 0 to achieve the same effect as the first line across reboots.
  • @Emanuil: Thanks, I'll correct it.
  • Thanks guys. Everything is fine now.
  • Hi @Kamal, I see you changed both swappiness lines to 10. It's good that they are consistent now but the text still says "Swappiness in the file should be set to 0. Skipping this step may cause both poor performance, whereas setting it to 0 will cause swap to act as an emergency buffer, preventing out-of-memory crashes." zero. Is there a reason why swappiness on a server should be set to 10 instead of 0? Perhaps either: 1. Update text with that reason 2. Change the swappiness commands to set it to 0 instead of 10 Thanks!
  • @Emanuil: I can't believe I missed that. Thanks again! :] I'll fix it. A lot of users have been having issues with swappiness set to 0 which were fixed by setting it to 10.
  • thanks for this. wouldn't it be useful if the droplets were spun up with a swapfile/swap partition already enabled? 512MB for a 512MB instance 1GB for a 1GB instance etc. i've got another VPS with another provider and that's their policy. anyway...a minor quibble. loving the digitalocean service.
  • Awesome tutorial, this saved me from a database connection loss on Wordpress. Up and running after I did a reboot.
  • Thanks for this. I had a lack of memory end up crashing mysql and corrupting one of my tables. I was surprised to find that there was no swap space configured on my droplet. Fortunately, I had a backup from the day before, and thanks to this tutorial it's now got a nice 2 GB swap.
  • Is the example in the tutorial setting 512MB of SWAP? I'm confused by the "Setting up swapspace version 1, size = 262140 KiB" because I believe that 262140 KiB equals about 33MB.
  • Hi Craig, Thanks for catching that. The output and the commands do show different sizes. We'll update the article now.
  • @Craig Smith You can set the command "dd if=/dev/zero of=/swapfile bs=1G count=10" In my case it would be, setting a block size of 1GiB for each count of 10 = 10GiB of swapfile! In, your case, you'll need to set bs=1M count=33 it will create a 33MiB swapfile!
  • Etel Sverdlov you are a life saver :)
  • Thank you for the tutorial. I have used it at least 10 times so far to configure many servers. But I always skip the part about setting swappiness to 10. I also recommend that others do. When I did set swappiness to 10 the first time I did this, mysql used to crash when it ran out of memory. And other apps also behaved in a weird way. The os prefers to crash/remove certain files of these apps from memory rather than use swaps when swappiness is 10. Unless you're buying a droplet with 16+ GB ram(and depending o nthe worldload) I'd leave it at default PS: I like the "destroy" button on comments :P
  • Hi,

    can i use this procedure also on ubuntu 13.10 ?


  • Awesome! You’re a legend.

    See your swp in action with: htop

  • this might be a stupid question but should all 3 lines be added to the /etc/fstab file ?

    /swapfile none swap sw 0 0
    echo 10 | sudo tee /proc/sys/vm/swappiness
    echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf

    or did the instructions mean to just add

    /swapfile none swap sw 0 0

    and then enter the following 2 lines as commands once you’ve saved + exited out of nano?

    echo 10 | sudo tee /proc/sys/vm/swappiness
    echo vm.swappiness = 10 | sudo tee -a /etc/sysctl.conf

    Also does it matter where abouts in /etc/fstab the line(s) are added?
    eg. can they be inserted at line 1, or should they be added at the end on a new line after the text that is already in the file?


  • Guidelines to Install VPS DigitalOcean
    It is real discouraging that there are web hosting servers that don’t provide hosting services as required. These servers are mostly found to be slow and very expensive to maintain. DigitalOcean has the ability of offering first class VPS services.

  • Thanks alot! But I think I should better to upgrade my droplet to 2 GB instead 512 MB.

  • I use a lot of swap space. 1 What do I need to delete GB?

  • I follow every step on CentOS 6.5, but every time I reboot or power off, I have to follow it again.

    The fstab has the swapline but do not apply at system reboot.

  • some other tutorial used sysctl for checking and setting vm.swappiness. I think it’s better to use this one simple command for setting swappiness:
    sysctl -w vm.swappiness=30
    (than echo and tee twice)

  • Added swap file of 256K, but is still getting “Error establishing a database connection” on my site.
    I have droplet memory 2GB and Disk size 40GB. Thanks!

  • Why are swap files not created by default when you set up the servers? Seems a bit odd that a 512MB server would have no swap file.

  • So helpful thanks so much, was trying to install symfony on my droplet and this sorts out my memory issue.


  • Good example, helped my servers.

  • When I go to prepair the swapfile with

    sudo mkswap /swapfile

    It displays

    mkswap: /swapfile: warning: don't erase bootbits sectors
            on whole disk. Use -f to force.
    Setting up swapspace version 1, size = 262140 KiB
    no label, UUID=b6d95442-0c64-4aba-8a10-90e25ad73eb6

    So I cant progress from here, how can I fix this?
    When I run:

    sudo swapon /swapfile

    It gives me

    swapon: /swapfile: swapon failed: Operation not permitted
  • Saved me and MySQL!!

  • hi I been stack in step

    sudo swapon /swapfile
    swapon: /swapfile: insecure permissions 0644, 0600 suggested.
    swapon: /swapfile: found swap signature: version 1, page-size 4, same byte order
    swapon: /swapfile: pagesize=4096, swapsize=1073741824, devsize=1073741824
    swapon: /swapfile: swapon failed: Operation not permitted

    chown to root and chmod 777 for /swapfile . but still error
    I renew server and install again again and again. it still have that bug. It make me so tired :(

  • thanks so much.. now i know my server didn’t use any swap at all :)

  • Thanks!! save my life!!!

  • Very well explained! Thank you!

  • Thank! It helped me!

  • Thanks a lot!
    Finally, this article solved a big problem when installing or git cloning something to my Droplet.

  • Thanks! Bundle install without “Killed” now)

  • by Etel Sverdlov
    Linux swaps allow a system to harness more memory than was originally physically available. Here's how to set up a linux swap file on Ubuntu 12.04
Creative Commons License