Magento 2 is a resource-intensive application. The recommended memory_limit for Magento 2 is:

Check the Current PHP Memory Limit

To check the current PHP memory limit, create a phpinfo.php file:

<?php
phpinfo();
?>

Access it in your browser (http://yourdomain.com/phpinfo.php) and look for the memory_limit directive.

Alternatively, use the command line:

php -r "echo ini_get('memory_limit');"

Update PHP Memory Limit

Modify php.ini

1

Locate your php.ini file

php --ini
2

Open the file

sudo nano /etc/php/7.x/fpm/php.ini # For PHP-FPM
sudo nano /etc/php/7.x/apache2/php.ini # For Apache
3

Find the memory_limit directive and increase the value

memory_limit = 2G
4

Save and exit

5

Restart your web server

sudo systemctl restart apache2 # For Apache
sudo systemctl restart php7.x-fpm # For Nginx with PHP-FPM

Modify .htaccess (Shared Hosting)

If you are on shared hosting, add this line to Magento 2 .htaccess file:

php_value memory_limit 2G

Modify PHP Command-Line Settings

Magento CLI commands often require a higher memory limit. Use the -d flag:

php -d memory_limit=2G bin/magento setup:upgrade

Modify in app/bootstrap.php

To temporarily override PHP settings for Magento 2:

  1. Open app/bootstrap.php.
  2. Add this line near the top:
  3. ini_set('memory_limit', '2G');

Verify Changes

Run the following command to confirm the new memory limit:

php -r "echo ini_get('memory_limit');"

You can also verify by running Magento CLI commands, such as:

php bin/magento setup:upgrade

Common Errors Related to Memory Limits

PHP Fatal Error: Allowed Memory Size Exhausted

If you encounter this error, it means the memory limit is too low. Increase it to 2G or more using the methods above.

Magento CLI Memory Exhaustion

When running Magento CLI commands like setup:upgrade or indexer:reindex, you might encounter memory issues. Always use:

php -d memory_limit=2G bin/magento <command>
  • Recommended Memory Limit: At least 2G for Magento 2.
  • Change in php.ini: For global settings.
  • Use -d in CLI: For Magento CLI commands requiring more memory.
  • Test Settings: Verify using phpinfo() or CLI.