I want to allocate memory to work as a swap file in an Amazon Elastic Compute Cloud (Amazon EC2) instance. 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 swap file that's designated for this purpose as swap space. This frees up RAM for more immediate use.

Swap space can also be created on a partition. For more information on using a partition or for a video on creating a swap file, see How do I allocate memory to work as swap space on an Amazon EC2 instance using a partition on my hard drive?

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

Calculate the swap space size

As a general rule, 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 swap file

1. Create a 4-GB swap file on the root file system, where "bs" is the block size and "count" is the number of blocks: 

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

2. Update the read and write permissions for the swap file: 

$ chmod 600 /swapfile

3. Set up a Linux swap area: 

$ mkswap /swapfile

4. Make the swap file available for immediate use by adding the swap file to swap space: 

$ swapon /swapfile

5. Verify that the procedure was successful: 

$ swapon -s

6. Enable the swap file at boot time by editing the /etc/fstab file:

$ vi /etc/fstab
$ /swapfile swap swap defaults 0 0

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