Magento often requires a higher PHP memory limit for resource-intensive tasks like setup:upgrade, indexer:reindex, or di:compile. Instead of permanently modifying the global php.ini, you can dynamically set the memory limit for specific Magento CLI commands.

Temporary Memory Limit via Command Line

To override the memory limit only for a single command, use the -d option with the php command:

php -d memory_limit=2G bin/magento <command>

Examples:

  1. Upgrade the Database:
  2. php -d memory_limit=2G bin/magento setup:upgrade
  3. Recompile Dependency Injection:
  4. php -d memory_limit=3G bin/magento setup:di:compile
  5. Reindex Data:
  6. php -d memory_limit=2G bin/magento indexer:reindex
  7. Run the Magento Cron Job:
  8. php -d memory_limit=2G bin/magento cron:run

Verify the Memory Limit in Magento CLI

To confirm the memory limit applied during a command, you can add a simple PHP command:

php -d memory_limit=2G -r "echo ini_get('memory_limit');"

Expected output: 2G

Use Environment Variables (For Recurring Tasks)

If you frequently run Magento CLI commands that require higher memory, you can set an environment variable to avoid specifying -d memory_limit every time:

1. Set an Environment Variable Temporarily:

export PHP_MEMORY_LIMIT=2G

Then run Magento commands like this:

php bin/magento setup:upgrade

2. Set an Environment Variable Permanently:

Add this to your .bashrc or .zshrc file:

export PHP_MEMORY_LIMIT=2G

Apply the changes:

source ~/.bashrc

Combine with Other PHP Options

Magento CLI commands may also require other PHP configuration overrides. You can combine multiple -d options in a single command:

php -d memory_limit=3G -d max_execution_time=1800 bin/magento setup:upgrade

When to Use Command-Line Memory Limit

Best for One-Time or Debugging Tasks:

  • Useful for temporary operations, such as upgrades or reindexing.

Avoids Permanent Changes:

  • Prevents system-wide changes to php.ini.

Troubleshooting Common Issues

Memory Exhaustion Errors

Error: PHP Fatal error: Allowed memory size of X bytes exhausted.

Solution: Increase the memory limit using:

php -d memory_limit=3G bin/magento <command>

Command Fails Without Error

Solution: Check your PHP configuration:

php -r "phpinfo();"

Ensure the correct memory_limit is applied.

Global Configuration Takes Precedence

If the -d option does not work, ensure your system does not override settings from /etc/php-cli.ini or similar files.

To dynamically adjust PHP memory limits for Magento CLI commands:

  1. Use php -d memory_limit=2G bin/magento <command>.
  2. Verify the applied memory limit with php -r "echo ini_get('memory_limit');".
  3. Set environment variables for recurring commands.