Magento 2 Environment Variables: Configuration Types & Uses

Magento 2 Environment Variables: Configuration Types & Uses

Want to manage Magento settings more efficiently across environments? Magento 2 environment variables help you implement system settings without modifying core files. They allow developers to simplify configuration, improve security, and ensure smooth performance.

This article will cover how environment variables simplify Magento configuration.

Best Magento Hosting now

Key Takeaways

  • Overview of Magento 2 environment variables and their significance in configuration management.
  • 10 different types of environment variables and their specific roles.
  • 2 ways to configure environment variables effectively.
  • 11 common use cases for deploying environment variables across various deployment modes.
  • 10 best practices for managing environment variables and managing store settings.
  • Troubleshooting common issues associated with environment variables.

What are Environment Variables in Magento 2?

Magento 2 environment variables are configuration settings stored outside the codebase. It enables efficient customization across development, staging, and production environments.

Magento 2 environment variables help manage necessary configurations without hardcoding sensitive data. Thus, they ensure security and flexibility.

Key configurations controlled by environment variables include:

  • Database credentials
  • Caching mechanisms
  • Session storage settings
  • Search engine configurations

These admin variables are defined in app/etc/env.php or set directly on the server. They enhance security, optimize deployments, & separate code from configuration for scalable & efficient management.

10 Different Types of Environment Variables in Magento Admin

Type Explanation
Database Configuration - DB_HOST: Specifies the database host address.
- DB_NAME: Defines the database name.
- DB_USER: Sets the username for database access.
- DB_PASSWORD: Secures the database with a password.
- DB_PREFIX: Adds a prefix for database tables, which is helpful for shared hosting.
Caching - CACHE_BACKEND: Configures the caching backend in Magento.
- CACHE_BACKEND_REDIS_SERVER: Specifies the Redis server address (if Redis is used).
- CACHE_BACKEND_REDIS_PORT: Defines the Redis server port.
- CACHE_BACKEND_REDIS_DATABASE: Sets the Redis database number for caching.
Session Management - SESSION_SAVE: Determines where sessions are stored.
- SESSION_SAVE_REDIS_HOST: Specifies the Redis server for session storage.
- SESSION_SAVE_REDIS_PORT: Defines the Redis port for session storage.
- SESSION_SAVE_REDIS_TIMEOUT: Sets a timeout for sessions.
- SESSION_SAVE_REDIS_DB: Specifies the Redis database for session storage.
Search Engine - SEARCH_ENGINE: Configures the search engine used by Magento (e.g., "Elasticsearch").
- ELASTICSEARCH_HOST: Sets the host address for Elasticsearch.
- ELASTICSEARCH_PORT: Defines the port for Elasticsearch connections.
Encryption and Security MAGENTO_CRYPT_KEY Sets the encryption key to secure sensitive data, such as:
- Customer information
- Payment details
Message Queue (RabbitMQ) - QUEUE_HOST: Defines the RabbitMQ host for asynchronous processing.
- QUEUE_PORT: Specifies the RabbitMQ port.
- QUEUE_USER and QUEUE_PASSWORD: Set credentials for RabbitMQ access.
File System Configuration - MEDIA_DIRECTORY_PATH: Specifies the path for media storage (e.g., "images").
- STATIC_DIRECTORY_PATH: Sets the path for static files like CSS and JS.
- VAR_DIRECTORY_PATH: Defines the path for temporary files and cache storage.
Cron Jobs and Scheduled Tasks CRON_CONSUMERS_RUNNER: Configures settings for running background tasks like:
- Indexing
- Email sending through Magento's cron job runner
Debug and Developer Settings - MAGE_MODE: Defines whether Magento runs in developer, production, or default mode.
- X_FRAME_OPTIONS: Controls if your site can be embedded in iframes (security feature).
- ERROR_REPORTING: Sets error reporting levels that are helpful during debugging.
Email and Communication - SMTP_HOST: Specifies the SMTP server used to send emails.
- SMTP_PORT: Sets the port for SMTP connections.
- SMTP_USER and SMTP_PASSWORD: Configure authentication details for secure email delivery.

7 Benefits of Using Magento 2 Environment Variables

1. Scalability and Flexibility Across Environments

Magento 2 environment variables allow you to adapt configurations based on your environment. It also helps you switch development/staging/production settings without touching the codebase.

For example:

  • Configure separate database connections for staging and production systems.
  • Adjust caching settings for different store views or websites dynamically.

This flexibility allows your Magento store to scale while ensuring smooth operations.

2. Enhanced Security for Sensitive Data

Security is non-negotiable in eCommerce. Magento 2 environment variables help you keep sensitive data safe. They allow you to manage them securely through environment variables. You don't need to hardcode information like database credentials/API keys/encryption keys.

This approach:

  • Reduces the risk of exposing sensitive data in source control systems like 'Git'
  • Protects your store from unauthorized access or data leaks

3. Simplified Deployments Without Modifying Codebase

Deployments can be challenging if you’re constantly editing configuration files. Environment variables eliminate this issue by allowing you to manage settings dynamically.

For instance:

  • You can override default configurations without modifying core files.
  • Deployment becomes faster and less error-prone since all settings are managed externally.

4. Dynamic Configuration Management

Magento 2 environment variables allow you to adjust configurations quickly. For example, if you need to change session storage from files to Redis, you can do so easily. Similarly, if you want to update database credentials, you can do so easily.

With environment variables, you can:

  • Quickly override default values without clearing cached settings manually.
  • Manage complex configurations like multi-threaded indexing (MAGE_INDEXER_THREADS_COUNT) efficiently.

5. Improved Team Collaboration

Consistency is key when multiple teams work on a Magento project. Environment variables provide a standardized way to manage configurations across environments. For example, Pro Staging and Production.

Benefits include:

  • Shared naming conventions for better understanding among developers and admins.
  • Centralized variables management through .magento.env.yaml, making it easier to document & collaborate.

6. Support for Hierarchical Variables

Magento 2 environment variables are hierarchical by design. It means they inherit values from the parent environments unless explicitly overridden. This structure ensures flexibility while maintaining consistency across environments.

For example, a global set variable applies during deployment unless overridden. You can define a global variable like GLOBAL_LOGGING_LEVEL=info in magento.env.yaml. This value will apply to all environments by default unless overridden in staging.

7. Optimized Cloud Integration

Environment variables simplify configuration management and enhance efficiency when using Adobe Commerce Cloud.

Consider the following practices:

  • Use .magento.env.yaml to customize build, deploy, & post-deploy actions across all environments.
  • Manage admin-specific variables from the Cloud Console or CLI without needing support tickets.
  • Override configuration options dynamically with cloud-specific variables like MAGENTO_CLOUD_RELATIONSHIPS.

Advanced Configuration Values in Magento Commerce Cloud

Variable Name Possible Values Version Constraints Explanation
MAGE_RUN_TYPE store, website (string) 2.* CE, 2.* EE Defines the scope (website or store view) for the current request
MAGE_RUN_CODE Any valid store/website code (string) 2.* CE, 2.* EE Specifies the website/store code for the current request. Note: Use admin for admin requests.
MAGE_MODE developer, default, production 2.* CE, 2.* EE Determines the mode Magento is running in. Note: default mode is deprecated.
MAGE_PROFILER true, false (boolean) 2.* CE, 2.* EE Enables or disables the Magento profiler for performance analysis
MAGE_DEBUG_SHOW_ARGS true, false (boolean) 2.* EE Includes arguments in exception reports for debugging purposes
MAGE_REQUIRE_MAINTENANCE true, false, or null 2.* EE Controls maintenance mode:

- true: Requires maintenance
- false: Disables maintenance
- null: Skips the check
MAGE_REQUIRE_IS_INSTALLED true, false, or null 2.* EE Similar to maintenance mode but checks if Magento is installed:

- true: Requires installation.
- false: Disables installation check.
- null: Skips the check.
INIT_PARAM_FILESYSTEM_DRIVERS Driver-specific values 2.* EE Configures filesystem drivers for advanced file handling in Magento environments
MAGE_DIRS Directory paths 2.* EE Specifies directory paths used by Magento for various operations like caching and logs
MAGE_INDEXER_THREADS_COUNT Integer value > 0 >2.2.6 EE Sets the "maximum no. of threads" allowed for running indexers to improve performance on large systems
MAGENTO_CLOUD_APP_DIR Absolute path Cloud Infrastructure Specifies the application directory path in Adobe Commerce Cloud environments
MAGENTO_CLOUD_APPLICATION_NAME String Cloud Infrastructure The name of the application as defined in .magento.app.yaml
MAGENTO_CLOUD_RELATIONSHIPS Base64-encoded JSON Cloud Infrastructure Represents key-value pairs of environment relationships such as database connections or endpoints
MAGENTO_CLOUD_VARIABLES Base64-encoded JSON Cloud Infrastructure A collection of custom key-value pairs to override configuration settings dynamically across environments
ADMIN Variables Admin-specific values All Environments Overrides admin settings like "username", "email", and "admin URL" through Cloud Console or CLI commands
Build Variables Build-stage-specific settings Cloud Infrastructure Control actions during the build phase using .magento.env.yaml
Deploy Variables Deploy-stage-specific settings Cloud Infrastructure Manage deploy actions like enabling/disabling modules/setting environment-specific configurations during deployment phases
Post-Deploy Variables Post-deploy-stage-specific settings Cloud Infrastructure Control actions after deployment like clearing caches/reindexing data, using .magento.env.yaml

11 Common Uses of Environment Variables in Magento Ecommerce

1. Database Configuration

Environment variables securely store database credentials, including:

  • Host
  • Username
  • Password

This approach prevents hardcoding sensitive data in the codebase, enhancing security. Different database settings can be applied for development, staging, and production environments. These settings can be configured without requiring any manual code changes.

2. Caching Mechanisms

Variables like CACHE_BACKEND and CACHE_BACKEND_REDIS_SERVER define caching configurations, optimizing speed and performance by:

  • Enabling different caching strategies across environments
  • Improving resource allocation and loading times

3. Session Management

Magento 2 environment variables specify where sessions are stored, improving performance & data management. Consider the following practices:

  • Secure session storage helps protect user data.
  • Adjust session settings dynamically without modifying core files.

4. Search Engine Configuration

Variables like SEARCH_ENGINE & ELASTICSEARCH_HOST define the search engine type and connection details by:

  • Enhancing on-site search capabilities
  • Adjusting search engine configurations across different environments

5. Encryption and Security

magento 2 environment variables securing encryption keys and sensitive data

The MAGENTO_CRYPT_KEY environment variable securely stores the encryption key for protecting sensitive data. Key benefits include:

  • Ensures secure transactions and communication
  • Allows you to configure security-related variables to strengthen overall application security

6. Message Queue Configuration

Environment variables such as QUEUE_HOST & QUEUE_PORT configure RabbitMQ for background task processing. They help:

  • Improve performance and scalability
  • Adjust queue settings without modifying code, ensuring flexible integration.

7. File System Configuration

magento 2 environment variables managing file system paths for media and cache storage

Environment variables define storage paths for:

  • Media files
  • Static content
  • Temporary files

This process ensures proper file storage and access across environments. Developers can easily switch file paths based on the environment, improving deployment efficiency.

8. Debugging and Developer Settings

The MAGE_MODE variable sets the Magento application mode, controlling error reporting & debugging settings. You can:

  • Enable logging and debugging without affecting the production system.
  • Manage error reporting levels dynamically.

9. Email Configuration

Environment variables store SMTP configuration settings, including:

  • Host
  • Port
  • Username & Password

This approach allows secure and flexible email configurations for transactional emails. It also helps keep sensitive credentials out of the codebase.

10. Custom Configuration

Magento 2 allows defining custom environment variables for specific application needs, such as:

  • API keys for third-party integrations
  • External service configurations

This flexibility enables smooth adaptation to various environments without hardcoded values.

11. Deployment Automation

Environment variables simplify Continuous Integration (CI) and Continuous Deployment (CD) processes. They enable dynamic configurations by:

  • Automatically applying different settings based on deployment environments
  • Managing configurations efficiently using deployment scripts and tools

How Do Environment Variables Work in Different Deployment Modes?

1. Default Mode

The default mode is the default operating mode when no specific mode is set. It is mainly used during initial installations and basic development.

Environment Variable Usage

  • Shared configuration parameters apply basic configurations with minimal optimizations.
  • Environment variables help define database connections and caching backends.
  • Security settings are less strict than in production but require storing sensitive data.

2. Developer Mode

The developer mode is customized for development and debugging. It allows developers to test changes quickly, view errors, and troubleshoot efficiently.

Environment Variable Usage

  • MAGE_MODE is set to the developer in server settings or app/etc/env.php.
  • Enhanced error reporting is enabled, displaying error messages & stack traces for faster debugging.
  • Static files (CSS, JavaScript) are served unminified, making code inspection easier.
  • Caching is minimized or disabled, allowing real-time changes without manual cache clearing.
  • Additional debugging tools and logging configurations can be managed via environment variables.

3. Production Mode

The production mode is designed for live environments, ensuring maximum security, performance, & stability.

Environment Variable Usage

  • MAGE_MODE is set to production through environment variables, ensuring optimized settings.

  • Environment variables enable secure connections and performance enhancements, such as:

    • Advanced caching configurations in Magento 2 (Redis, Varnish) to boost performance.
    • Minified and optimized static files, reducing page load times.
    • Database credentials and encryption keys stored securely as environment variables to prevent exposure.
    • Error messages are hidden from users.
    • Logging settings are controlled via environment variables to prevent sensitive data leaks.

Real-World Applications of Magento 2 Environment Variables

Scenario Explanation
Setting Up a Production System with Environment Variables Environment variables simplify the setup of production systems by externalizing sensitive data. Examples include database credentials and encryption keys. For example:

- Use DB_HOST and DB_PASSWORD to securely configure database connections.
- Set MAGE_MODE to "production" to optimize performance and disable developer tools.
Configuring Adobe Commerce Cloud Environments Adobe Commerce Cloud allows you to manage environment variables. You can do this through the Cloud Console or the .magento.env.yaml file. It enables:

- Customizing build, deploy, and post-deploy actions using variables like MAGENTO_CLOUD_RELATIONSHIPS
- Overriding default configurations dynamically without modifying core files
Optimizing Development with Version Control and Git Using environment variables ensures sensitive data is excluded from version control systems. For instance:

- Add .env files. containingDB_USER or API_KEYS to .gitignore.
- Use tools like phpdotenv to load environment variables dynamically during development. It helps make collaboration flexible across teams.
Customizing Caching Mechanisms Across Environments Variables like CACHE_BACKEND_REDIS_SERVER allow you to configure caching differently for the following environments:

- Development
- Staging
- Production

This scalability ensures optimal performance for each stage without manual intervention.
Managing Build and Deployment Phases with .magento.env.yaml The .magento.env.yaml file helps you define global, build-specific, deploy-specific, & post-deploy-specific variables. For example:

- Set GLOBAL_LOGGING_LEVEL for all phases.
- Use DEPLOY_ENABLE_MODULES to enable specific modules during deployment only.
Optimizing Multi-Store Setups For multi-store or multi-website setups in Magento, use environment variables like MAGE_RUN_TYPE & MAGE_RUN_CODE. These variables help dynamically define the scope (store or website) & code for requests. Thus, they ensure smooth operations across all stores.
Enhancing Security with Sensitive Data Management Store sensitive data in environment variables (e.g., MAGENTO_CRYPT_KEY). This approach helps you reduce the risk of exposing credentials in source control. It also enables you to maintain secure access across environments.
Automating CI/CD Pipelines Integrate environment variable management into CI/CD pipelines to automate deployment processes. For example, use scripts to set variables dynamically based on the deployment stage.

2 Methods to Configure Magento 2 Environment Variables

Method 1: Using the getenv() Function

Step 1: Define Environment Variables on the Server

  1. Set the necessary environment variables in your server configuration or hosting platform.
  2. Common variables to define:
  • Database Host: MYSQL_HOST
  • Database Name: MYSQL_DATABASE
  • Database Username: MYSQL_USERNAME
  • Database Password: MYSQL_PASSWORD

Step 2: Modify the env.php File

  1. Navigate to app/etc/env.php in your Magento 2 installation.
  2. Use getenv() to retrieve environment variables dynamically.

Step 3: Apply Changes and Verify

  1. Save the env.php file after making modifications.
  2. Flush the cache using the following command:

bin/magento cache:flush

  1. Test the changes by ensuring Magento loads the environment variables correctly.

Method 2: Configuring Through Magento Admin and CLI

Step 1: Set Configuration in the Magento Admin

  1. Log in to the Magento Admin Panel.
  2. Navigate to Stores > Settings > Configuration.
  3. Adjust environment-specific settings such as "Store Name", "VAT Number", and "Email Configurations".
  4. Save the changes and flush the cache if required.

Step 2: Export the Configuration

  1. Access the Magento root directory via SSH.
  2. Run the following command to export the configuration:

php bin/magento app:config:dump

  1. Verify the changes in app/etc/config.php and commit them to version control.

Step 3: Update the Build System

  1. Pull the latest configuration updates from source control.
  2. Compile code using:

bin/magento setup:di:compile

  1. Deploy static content for optimized performance using the following command:

bin/magento setup:static-content:deploy -f

Step 4: Apply Updates to the Production System

  1. Enable maintenance mode using the command given below:

bin/magento maintenance:enable

  1. Pull the latest configuration updates from version control.
  2. Import the configuration settings using the following:

bin/magento app:config:import

  1. Clear the cache and disable maintenance mode using:

bin/magento cache:clean

bin/magento maintenance:disable

Best Practices for Managing Environment Variables in Magento 2

Best Practice Explanation
Use Environment Variables for Sensitive Data - Store sensitive information like database credentials, API keys, and encryption keys.
- Avoid hardcoding them in files to reduce the risk of exposure in version control systems.
- Use variables like DB_USER, DB_PASSWORD, and MAGENTO_CRYPT_KEY.
Separate Configurations by Environment - Maintain separate configurations for development, staging, and production environments.
- Use different .env files or server configurations.
- Prevent accidental overwrites and ensure smooth transitions between environments.
Automate Deployment Processes - Use CI/CD pipelines/deployment scripts to set environment variables during deployment.
- Automate processes to ensure proper configurations are applied to the right environment.
Document and Version Control Variables - Keep a well-maintained list of all environment variables with clear purpose descriptions.
- Exclude sensitive variable files from version control by adding them to .gitignore. This documentation aids team collaboration and reduces errors.
Use Consistent Naming Conventions - Establish clear naming conventions for variables. For example, use prefixes like DB_ for database settings & CACHE_ for caching configurations.
- Use consistent names to make identifying and managing variables easier across environments.
Review and Audit Regularly - Periodically audit your environment variables to ensure they are still relevant and secure.
- Remove unused variables, update outdated ones, & conduct security reviews for production environments.
Use Environment Variable Libraries - Use libraries like phpdotenv to manage environment variables efficiently.
- Simplify loading values from .env files & provide better control in PHP applications.
Control Access to Environment Variables - Restrict access to sensitive environment variables using server-level permissions.
- Ensure authorized personnel can view/modify these values, especially in production systems.
- Use separate user accounts for different environments when necessary.
Use Default Values as Fallbacks - Define default values for sensitive environment variables in your application code.
- Ensure the application runs if some variables are unset during deployment/testing.
Test Environment Variables Thoroughly - Before deploying changes, test your environment variable configurations in a staging environment.
- Verify that all variables are properly set and that the application behaves as expected.
- Have rollback procedures ready in case of issues during deployment.

FAQs

1. How can you use environment variables to override configuration settings?

You can use environment variables to override configuration settings without modifying core files. Define variables in the server or env.php file. Magento fetches these values during execution. This method prevents the hardcoding of sensitive data. It also helps manage configurations across development, staging, and production environments.

2. What types of settings can be managed using environment variables?

Various settings using environment variables include database credentials, caching, session storage, & security keys. Developers can also configure search engines, file storage, API keys, and SMTP settings. These variables improve flexibility by separating configuration from code. They allow quick adjustments without directly modifying files.

3. How does Adobe Commerce CLI support environment variable management?

The Adobe Commerce CLI helps manage Magento settings through commands. It allows developers to import, export, and modify configurations. Environment variables can be set via CLI commands for automated deployments. This tool helps simplify system management without manual code modifications.

4. Why is indentation a must when setting environment variables?

Proper indentation in configuration files ensures variables are read correctly. YAML and JSON files require consistent spacing and structure. Incorrect indentation can break configurations, cause parsing errors, or affect system behavior. Magento interprets these files based on proper formatting.

5. Can environment variables manage settings specific to checkout processes?

Yes, environment variables can handle settings specific to the checkout process. They define payment gateways, tax calculations, and shipping methods. These variables help customize checkout configurations across multiple store views and websites. Developers can update settings dynamically without changing the code.

6. How do environment variables affect privacy policy and database security?

Environment variables enhance privacy policy compliance and DB security. They store database credentials, encryption keys, and sensitive customer data outside the codebase. This method prevents exposure in version control systems. Magento uses these variables to authenticate connections and restrict unauthorized access securely.

CTA

Summary

Using Magento 2 environment variables, you can override configuration settings & manage sensitive data. They empower developers and administrators to

  • Control system settings without altering core files.
  • Customize configurations for development, staging, and production environments, enhancing flexibility and security.
  • Use environment variables to optimize deployment processes.
  • Regularly test and audit environment variables to ensure security.
  • Securely manage database credentials and encryption keys.
  • Optimize performance by configuring caching and session variables.
  • Leverage message queues for efficient background processing.
  • Adjust configurations to ensure flexible deployments.

Configure environment variables and enhance performance with managed Magento hosting.

Dikshya Shaw
Dikshya Shaw
Technical Writer

Dikshya leverages her content marketing and writing proficiency to deliver fresh, insightful content. Her meticulous research ensures industry expertise and emerging trends within the Magento landscape.


Get the fastest Magento Hosting! Get Started