proc_open(): fork failed - Cannot allocate memory

Sometimes, when you run any composer command in Laravel project, you may get error 'proc_open(): fork failed - Cannot allocate memory'. Here is the full error I got when running command composer update:

Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:975

This could be happening because the VPS runs out of memory and has no Swap space enabled. You can check the current memory and swap using command:

free -m

It will return memory like below: 

total used free shared buffers cached
Mem: 2048 255 1792 0 0 277
Swap: 0 0 0

You need to enabled swap with following commands:

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

If the above commands not work, then you can try to create a swap file.

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

And now you can use composer command.