Why don’t EC2 ubuntu images have swap?

You are right, the Ubuntu EC2 EBS images don’t come with swap space configured (for 11.04 at least). The “regular” instance-type images do have a swap partition, albeit only 896 MB on the one I tested.

If some process blows up and you don’t have swap space, your server could come to a crawling halt for a good while before the OOM killer kicks in, whereas with swap, it merely gets slow. For that reason, I always like to have swap space around, even with enough RAM. Here’s your options:

  • Create an EBS volume (2-4 times the size of your RAM), attach it to your instance (I like calling it /dev/xvdm for “memory”), sudo mkswap /dev/xvdm, add it to fstab, sudo swapon -a, and you’re good to go. I have done this before and it works fine, but it is probably a bit slower than instance store because it goes over the network.

  • Or you might be able to repartition your disk to add a swap partition, though this might require creating a new AMI. I have not been able to do this in a running instance, because I cannot unmount the root file system, and I do not even have access to the disk device (/dev/xvda), only the partition (xvda1).

  • Or you can create a swap file. This is my preferred solution right now.

    sudo dd if=/dev/zero of=/var/swapfile bs=1M count=2048 &&
    sudo chmod 600 /var/swapfile &&
    sudo mkswap /var/swapfile &&
    echo /var/swapfile none swap defaults 0 0 | sudo tee -a /etc/fstab &&
    sudo swapon -a
    

    Done. 🙂 I know a lot of people feel icky about using files instead of partitions, but it certainly works well enough as emergency swap space.

Leave a Comment