I want to allocate memory to work as swap space on an Amazon Elastic Compute Cloud (Amazon EC2) instance using a partition on my hard drive. How do I do that?

Swap space is commonly used as a short-term replacement for physical RAM on an Amazon EC2 instance that's experiencing demand for physical RAM that is currently occupied by data, or instructions from applications, or the operating system.

Contents of RAM that aren't in active use or that aren't needed as urgently as other data or instructions can be temporarily paged to a partition that's designated for this purpose as swap space. This frees up RAM for more immediate use.

Swap space can also be created using a swap file. For more information, see How do I allocate memory to work as swap space in an Amazon EC2 instance by using a swap file?

Note: It's a best practice that you create swap space only on ephemeral storage instance store volumes. 

Calculate the swap space size

Swap space should equal 2x the physical RAM, for up to 2 GB of physical RAM, and then an additional 1x physical RAM for any amount above 2 GB. Swap space should never be less than 32 MB.

Amount of system RAM Recommended swap space
2 GB of RAM or less 2x the amount of RAM but never less than 32 MB
More than 2 GB of RAM but less than 32 GB 4 GB + (RAM – 2 GB)
32 GB of RAM or more 1x the amount of RAM

Create a partition on your hard drive as swap space

1. Log in to the instance using SSH.

2. List the available volumes:

sudo fdisk -l

3. Select a device to partition from the list. In this example, use the device /dev/xvda.

$ sudo fdisk /dev/xvda

4. Create a new partition:

-> n

5. Select a partition type. In this example, use primary:

-> p

6. Assign the partition number. In this example, use partition 2:

-> 2

7. Accept the default of "First sector" by pressing Enter.

8. Manually enter the size of the swap file. For this example, there is 2 GB RAM, and the partition created is 4 GB (specified as +4G).

-> +4G

9. Save and exit:

-> w

Set up the swap area

1. Use the partprobe command to inform the OS of partition table change:

$ partprobe

2. Set up a Linux swap area. Because the second partition in the earlier steps was created to be used as swap partition, use /dev/xvda2:

$ mkswap /dev/xvda2

3. Add the partition as swap space:

$ sudo swapon /dev/xvda2

4. Show the current swap space.

$ sudo swapon -s

Output similar to this should appear:

Filename                Type        Size      Used    Priority
/dev/xvda2              partition   4194300   0       -1

5. Make the swap memory allocation permanent after reboot:

$ sudo vim /etc/fstab
$ /dev/xvda2 none swap sw 0 0
$ reboot 

Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2018-08-30