Adding Swap to an EC2 Micro Instance

EC2 micro instances come with no swap by default – at least every micro instance that I’ve ever launched does, I’m not sure if it’s theoretically possible to launch an instance with swap. The lack of swap is probably a side-effect of the limited memory combined with EBS-only storage and concomitant risk of high EBS charges if you swap heavily.

However, if you’re willing to accept the risk of unexpected high EBS I/O costs, it’s straightforward to add swap:

# /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
# /sbin/mkswap /var/swap.1
# /sbin/swapon /var/swap.1

Or, if you prefer Puppet:

class swapfile {

  exec { "create swap file":
    command => "/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024",
    creates => "/var/swap.1",
  }

  exec { "attach swap file":
    command => "/sbin/mkswap /var/swap.1 && /sbin/swapon /var/swap.1",
    require => Exec["create swap file"],
    unless => "/sbin/swapon -s | grep /var/swap.1",
  }
  
}
Advertisement

10 comments

  1. Sandeep Dhapte

    Hi,

    I have m1.large server instace with 0 swap. Currently it is using physical memory. I want to add swap file on the server, Can i add swap file manually on Live server with following method ??

    dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
    mkswap /var/swap.1
    swapon /var/swap.1

    Please suggest asap.

    Thanks
    Sandy

  2. Andy

    @Sandeep – This method should also work for an m1.large instance; of course, you may want to test it on a non-production instance first, verify you have enough disk space, etc.

  3. Shahnawaz

    Hi,

    I got a m1.xlarge instance and we created swap memory to 24G but unusual thing is that it won’t use swap even physical memory is 100%.
    Please suggest.

    Thanks,
    Shah

  4. Andy

    @Shahnawaz – How are you determining that swap isn’t used and physical memory is 100% consumed? What does “free -m” report? Is what’s actually consuming the memory swappable?

  5. Pingback: Beta EC2 » Day 7
  6. Andy

    @Javier – You can (and probably should) use ephemeral storage on other instance types for swap, but there’s no ephemeral storage on t1.micro instances.

  7. Pingback: Moving extricate.org to Amazon EC2 – extricate.org
  8. Martijn Heemels

    Thanks for showing that example class. I’ve expanded it a bit with some parameters, such as: ensure, path, and size. I’ve also added some documentation.

    I’ve posted this new class here: https://gist.github.com/3918632 and would appreciate any feedback.

    The main thing that’s missing is managing /etc/fstab to ensure that swap is mounted at boot. Right now, it depends on a puppet run.