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
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 RAM | Recommended Swap Size |
---|---|
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 |
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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)