Solving out of memory errors with PHP and Composer on EC2s free tier
For one of my recent projects, I wanted to make use of the free allowance that AWS gives for SES.
One of the conditions of the SES allowance was that your calling app needs to be hosted on EC2.
I’ve not used EC2 before so I figured this would be a good way to dive into it.
Whilst I would never usually install software like a composer on a production server, this was pure to test things out.
So after signing up for AWS and creating a local ubuntu server on an EC2 t2micro instance then cloning down the project I ran composer install to come across the following message:
822091776bytes is over 800mb of memory being consumed by the composer.
Whilst php-fpm has a 128mb max memory limit per script by default,
php-cli has a value of -1 which means use unlimited memory.
In this instance attempting to allocate over 800mb of memory on a server with 1gb was not going to end well.
The solution was to create a swap file on the disk.
A swap file or partition is space on disk allocated that can be used when the physical memory allocation is exhausted. Once the allocation is exhausted, older items in memory get offloaded to the swap partition.
The actual solution for this I found over on this GitHub issue.
The following code will create a 1gb swap file in
/var/swap.1 for our instance to use
sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024