Allocate Memory as Swap File in Amazon EC2

In this article, I’m going to talk about how to allocate memory to work as a swap file in an Amazon Elastic Compute Cloud (Amazon EC2) instance.

Table of Contents

  1. Problem
  2. Solution
  3. Swap Space Size
  4. Add Swap Space

Problem

In Amazon EC2, sometimes we face this type error ‘mmap() failed: [12] Cannot allocate memory‘. We may face this issue at the time of using composer, npm too. If your server has low RAM, then you may face this issue.

Solution

To solve this issue, you can upgrade your RAM. It’ll solve the issue. Otherwise, you can create a swap file. The Swap file allows your computer’s operating system to pretend that you have more RAM than you actually do. If you’ve higher RAM, then I recommend to create a swap file too.

Swap Space Size

Swap space should never be less than 32 MB. Let’s calculate swap space according to the following:

Server RAMRecommended Swap Size
2 GB of RAM or less2x the amount of RAM but never less than 32 MB
More than 2 GB of RAM but less than 32 GB4 GB + (RAM – 2 GB)
32 GB of RAM or more1x the amount of RAM

You can also set this size:

Swap File Size = [(2 x  RAM) + 1 MB]

Add Swap Space

Login to your EC2 server. Let’s think our server RAM is 1GB. So, recommenbed swap file size is 2GB. Run this command to create 2GB swap file:

sudo dd if=/dev/zero of=/swapfile bs=128M count=16

We can write bs=1M count=2048 too. Now run these commands:

# set permissions
sudo chmod 600 /swapfile

# Set up a Linux swap area
sudo mkswap /swapfile

# Make the swap file available
sudo swapon /swapfile

Now verify that the procedure was successful:

sudo swapon -s

Lastly we need to enable swap at boot time. Edit /etc/fstab file:

sudo nano /etc/fstab

At the end of the file, add this line and save:

/swapfile swap swap defaults 0 0

Now you can see your swap size by typing:

free -m
# or
htop

That’s it. Thanks for reading.