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:
Examples:
- Upgrade the Database:
- Recompile Dependency Injection:
- Reindex Data:
- Run the Magento Cron Job:
Verify the Memory Limit in Magento CLI
To confirm the memory limit applied during a command, you can add a simple PHP command:
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:
Then run Magento commands like this:
2. Set an Environment Variable Permanently:
Add this to your .bashrc or .zshrc file:
Apply the changes:
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:
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:
Command Fails Without Error
Solution: Check your PHP configuration:
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.


