Fix Composer Memory Exhausted errors

I had the following error trying to install Magento 2 community edition using Composer on a 2GB RAM debian linux server

composer create-project --repository-url= magento/project-community-edition ./

The errors resulting from this were

mmap() failed: [12] Cannot allocate memory
PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <…>

I checked my php-cli memory limit in /etc/php/7.2/cli/php.ini and it was set to unlimited (-1) so this clearly wasn’t the issue

I then tried

COMPOSER_MEMORY_LIMIT=-1 composer create-project --repository-url= magento/project-community-edition ./

This didn’t work either which is hardly suprising as php memory was already set to unlimited.

I was finally able to resolve the issue by creating a 1GB swap on my cloud server after trying various unsuccessful fixes. If you want to fix this quickly and already have unlimited memory set in php.ini this should fix.

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

Running the below command now worked perfectly

composer create-project --repository-url= magento/project-community-edition ./

Hope this saves you going round in circles trying to resolve the error