Modify PHP Memory Limit for Magento via Command-Line Settings
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.
For closely related Magento PHP-memory topics, see How to Update PHP Memory Limit for Magento 2 and Magento CLI PHP Memory Limit.
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:
- Upgrade the Database:
- Recompile Dependency Injection:
- Reindex Data:
- Run the Magento Cron Job:
php -d memory_limit=2G bin/magento setup:upgrade
php -d memory_limit=3G bin/magento setup:di:compile
php -d memory_limit=2G bin/magento indexer:reindex
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.
Recommended Memory Limits for Magento
- Production Environment: 2G (2048M)
- Development Environment: 3G (3072M) or higher for large catalogs.
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:
- Use
php -d memory_limit=2G bin/magento <command>. - Verify the applied memory limit with
php -r "echo ini_get('memory_limit');". - Set environment variables for recurring commands.


