How do I allocate memory to work as swap space on an Amazon EC2 instance using a partition on my hard drive?
Last updated: 2020-05-13
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?
Short Description
To allocate memory as swap space, do the following:
1. Calculate the swap space size.
2. Create a partition on your hard disk as swap space.
3. Set up the swap area.
You can also create a swap file to use as a swap space. 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 to create swap space only on ephemeral storage instance store volumes.
Resolution
Calculate the swap space size
Swap space should equal 2x the physical RAM, for up to 2 GB of physical RAM. For any amount above 2 GB, add an additional 1x physical RAM. 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 of 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 using the swap partition you created in the preceding steps. In this example, the swap partition is /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 the following appears:
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 article help you?
Anything we could improve?
Need more help?