Creating a swap file on an Amazon EC2 instance

By Philip Knerr

Introduction

Nowadays, even the most basic desktop or laptop computer has a fair amount of memory. This is not always the case for Amazon EC2 instances. The memory and other resources on a physical computer are typically divided among multiple EC2 instances. This saves you money, but it means your EC2 instance may have limited memory.

Creating a swap file acts as an insurance policy in case your Amazon EC2 instance temporarily needs more memory. This is especially important on smaller AWS instances, such as t2.micro and t2.nano, which have limited memory. The swap file can serve as memory if the memory allocated to an EC2 instance is full. Swap files are much slower than real memory, but this is better than crashing due to being out of memory.

The context and caveats in the Foreword apply to this article.

This information is current as of September 2, 2017.

Requirements

This article assumes you have already instantiated an Amazon EC2 instance on which you would like to create a swap file.

Creating a swap file

The following steps create a swap file which is one gigabyte in size. This size provides a margin of safety for many application servers.

First, create a 2 gigabyte file filled with all zeroes by executing the following command:

sudo dd if=/dev/zero of=/swap bs=1M count=2048

N.B. To create a swap file with a different size, you can change the number after count= to the desired size in megabytes.

This will take a few seconds. When finished, output similar to the following will be displayed:

2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 32.2632 s, 66.6 MB/s

Then, initialize the swap file by executing the following command:

sudo mkswap /swap

It will respond quickly, with output similar to the following:

Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=9ccb71c3-be33-4c61-8679-2c89ac7a79fc

For security reasons, disallow anyone but the root user from accessing the swap file. Execute the following command:

sudo chmod 600 /swap

Then, activate the swap partition by executing the following command:

sudo swapon /swap

Conclusion

The memory available to the EC2 instance now has a margin of safety equal to the size of the swap file. That said, it’s still better to allocate enough actual memory to meet the needs of the EC2 instance in most situations. Because using the swap file results in a performance hit, it is better to use it mostly for situations where the system temporarily needs more memory than usual.

–Phil Knerr