Magento 2 Environment Variables: Complete Configuration Guide
[Updated: March 23, 2026]
One wrong database credential in your env.php file takes your entire store offline. Environment variables in Magento 2 prevent that by separating sensitive configuration from your codebase.
This guide covers the env.php file structure, all configuration nodes, OS-level overrides with the CONFIG__ prefix, and deployment mode setup for Magento 2.4.8.
Key Takeaways
- Magento 2 stores environment-specific configuration in
app/etc/env.php, separate fromconfig.php. - The env.php file contains 18 top-level configuration nodes for database, cache, session, search, and security settings.
- OS-level environment variables use the
CONFIG__DEFAULT__SECTION__GROUP__FIELDnaming convention to override store configuration. - Magento 2.4.8 requires PHP 8.3/8.4, MySQL 8.4, OpenSearch 2, and supports Valkey 8 as a Redis alternative.
- Three deployment modes (developer, default, production) control error reporting, caching, and static file behavior.
What Are Magento 2 Environment Variables?
Magento 2 environment variables = configuration settings stored in
app/etc/env.phpthat control database connections, caching, sessions, and security outside your codebase. They let you run different configurations per environment without changing code.Perfect for: Store owners managing multiple environments, DevOps teams automating deployments, developers who need secure credential storage.
Not ideal for: Static single-environment setups where configuration never changes.
Magento 2 splits its configuration between two files:
| File | Purpose | Source Control |
|---|---|---|
config.php |
Module list, shared settings, themes | Yes (commit this) |
env.php |
Credentials, cache backends, encryption keys | No (keep out of Git) |
The env.php file holds everything environment-specific: database host and password, Redis connection details, search engine endpoints, and the encryption key that protects customer data. This separation ensures you never expose credentials in your repository.
env.php Configuration Nodes
The env.php file contains 18 top-level configuration nodes. Each controls a distinct part of the Magento system.
Database Configuration (db)
The db node defines all database connections:
'db' => [
'table_prefix' => '',
'connection' => [
'default' => [
'host' => 'localhost',
'dbname' => 'magento',
'username' => 'magento_user',
'password' => 'secure_password',
'model' => 'mysql4',
'engine' => 'innodb',
'initStatements' => 'SET NAMES utf8;',
'active' => '1',
]
]
],
Magento 2.4.8 supports MySQL 8.4 and MariaDB 11.4. Store database credentials here instead of hardcoding them in custom modules or deployment scripts.
Cache Configuration (cache)
The cache node configures frontend caching backends:
'cache' => [
'frontend' => [
'default' => [
'id_prefix' => 'mgt_',
'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis',
'backend_options' => [
'server' => '127.0.0.1',
'database' => '0',
'port' => '6379',
],
],
'page_cache' => [
'id_prefix' => 'mgt_',
'backend' => 'Magento\\Framework\\Cache\\Backend\\Redis',
'backend_options' => [
'server' => '127.0.0.1',
'database' => '1',
'port' => '6379',
'compress_data' => '1',
],
],
],
],
Magento 2.4.8 supports Redis 7.2 and introduces Valkey 8 as a drop-in Redis alternative. Learn how to configure Redis for Magento cache and session storage in our setup guide.
Session Storage (session)
'session' => [
'save' => 'redis',
'redis' => [
'host' => '127.0.0.1',
'port' => '6379',
'database' => '2',
'timeout' => '2.5',
],
],
Use a separate Redis database for sessions (database 2 in this example) to prevent cache flushes from destroying active user sessions.
Search Engine (catalog/search)
Magento 2.4.8 defaults to OpenSearch 2. Elasticsearch 8.17 remains supported for on-premises installations only:
'system' => [
'default' => [
'catalog' => [
'search' => [
'engine' => 'opensearch',
'opensearch_server_hostname' => 'localhost',
'opensearch_server_port' => '9200',
],
],
],
],
For search engine setup details, see our guide on configuring Magento 2 Elasticsearch and OpenSearch.
Encryption and Security (crypt)
'crypt' => [
'key' => 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6',
],
The encryption key protects passwords, payment data, and integration tokens. Generate this key during installation and never share it. Rotating the key requires re-encrypting all stored sensitive data.
All 18 Configuration Nodes
| Node | Purpose |
|---|---|
backend |
Admin panel URL prefix (frontName) |
cache |
Cache backend configuration (Redis, Valkey, file) |
cache_types |
Enable/disable individual cache types |
consumers_wait_for_messages |
Message queue consumer behavior (0 or 1) |
cron |
Cron job enable/disable flag |
crypt |
Encryption key for sensitive data |
db |
Database connections and credentials |
default_connection |
Message queue broker (db, amqp, stomp) |
directories |
Document root configuration |
downloadable_domains |
Allowed domains for downloadable products |
install |
Installation timestamp |
lock |
Lock provider settings |
MAGE_MODE |
Application deployment mode |
queue |
Message queue topics and connections |
resource |
Resource-to-connection mapping |
session |
Session storage handler and settings |
system |
System configuration overrides |
x-frame-options |
Clickjacking protection header value |
Override Configuration with OS Environment Variables
Magento 2 environment variables can also be set at the OS level to override store configuration without editing files. This is powerful for CI/CD pipelines and containerized deployments where you inject settings at runtime.
The CONFIG__ Naming Convention
The format follows this pattern:
CONFIG__<SCOPE>__<SECTION>__<GROUP>__<FIELD>
Scope options:
-
CONFIG__DEFAULT__for global (default) scope -
CONFIG__WEBSITES__<CODE>__for website scope
Converting a config path to an environment variable:
| Admin Path | Config Path | Environment Variable |
|---|---|---|
| Contact email recipient | contact/email/recipient_email |
CONFIG__DEFAULT__CONTACT__EMAIL__RECIPIENT_EMAIL |
| Store name | general/store_information/name |
CONFIG__DEFAULT__GENERAL__STORE_INFORMATION__NAME |
| Email domain (per website) | customer/create_account/email_domain |
CONFIG__WEBSITES__BASE__CUSTOMER__CREATE_ACCOUNT__EMAIL_DOMAIN |
Rule: Replace every / with __ (double underscore) and uppercase everything.
Setting Variables in PHP
In pub/index.php or your server configuration:
$_ENV['CONFIG__DEFAULT__CONTACT__EMAIL__RECIPIENT_EMAIL'] = 'admin@example.com';
Setting Variables in Server Configuration
Nginx:
fastcgi_param CONFIG__DEFAULT__WEB__SECURE__BASE_URL "https://store.example.com/";
Docker Compose:
environment:
- CONFIG__DEFAULT__WEB__SECURE__BASE_URL=https://store.example.com/
This approach works well for Docker-based Magento development environments where each container needs different configuration.
Deployment Modes and MAGE_MODE
Magento 2 environment variables include MAGE_MODE, which controls how the application handles errors, static files, and caching. Three modes are available.
Developer Mode
bin/magento deploy:mode:set developer
- Errors display in the browser with full stack traces
- Static files generate on every request (no pre-compilation needed)
- Cache disabled or minimal for real-time code changes
- Slower performance but faster development cycles
Default Mode
bin/magento deploy:mode:set default
- Errors logged to files, not displayed to visitors
- Static files generated on first request, then cached
- Basic caching enabled
- Used during initial installation
Production Mode
bin/magento deploy:mode:set production
- Errors hidden from visitors, logged to
var/log/ - Static files must be pre-deployed before going live
- Full caching enabled (Redis, Varnish, full-page cache)
- Maximum performance, strictest security
Check current mode:
bin/magento deploy:mode:show
Set the mode via environment variable instead of CLI:
// In env.php
'MAGE_MODE' => 'production',
Or as an OS variable: export MAGE_MODE=production
Magento 2.4.8 System Requirements
Every component in this table connects to Magento through env.php configuration nodes.
| Component | Required Version |
|---|---|
| PHP | 8.4, 8.3 |
| Composer | 2.9.3+ |
| MySQL | 8.4 |
| MariaDB | 11.4 |
| OpenSearch | 2 |
| Elasticsearch | 8.17 (on-premises only) |
| Redis | 7.2 |
| Valkey | 8 (new) |
| RabbitMQ | 4.1 |
| nginx | 1.28 |
A managed Magento hosting provider pre-configures these services and their corresponding Magento 2 environment variables, so you do not need to manage env.php entries for infrastructure components.
Message Queue Configuration (RabbitMQ)
For stores that process orders, emails, or inventory updates asynchronously:
'queue' => [
'amqp' => [
'host' => 'rabbitmq.example.com',
'port' => '5672',
'user' => 'magento',
'password' => 'queue_password',
'virtualhost' => '/',
],
],
The consumers_wait_for_messages node controls whether queue consumers wait for new messages (1) or exit after processing the current batch (0). Set to 0 in cron-based setups to prevent idle processes.
Best Practices for env.php Management
1. Never Commit env.php to Version Control
Add app/etc/env.php to .gitignore. This file contains database passwords, encryption keys, and API credentials. Committing it exposes every secret to anyone with repository access.
2. Use Separate Configurations Per Environment
Maintain different env.php files for development, staging, and production. Key differences:
| Setting | Development | Production |
|---|---|---|
MAGE_MODE |
developer | production |
cache backend |
file | Redis/Valkey |
session save |
files | redis |
| Database | Local MySQL | RDS/Aurora |
3. Use getenv() for Dynamic Values
Make env.php read from OS-level variables for portable configuration:
'db' => [
'connection' => [
'default' => [
'host' => getenv('MYSQL_HOST') ?: 'localhost',
'dbname' => getenv('MYSQL_DATABASE') ?: 'magento',
'username' => getenv('MYSQL_USER') ?: 'root',
'password' => getenv('MYSQL_PASSWORD') ?: '',
]
]
],
This pattern lets you commit env.php while injecting credentials at runtime through Docker, Kubernetes, or server environment variables.
4. Export and Import Configuration
# Export current config to config.php
bin/magento app:config:dump
# Import configuration on deployment
bin/magento app:config:import
The config:dump command writes shared settings to config.php (for version control) and keeps sensitive values in env.php (excluded from Git).
5. Test Configuration Changes in Staging First
Always verify env.php changes in a staging environment before production. A wrong Redis port or database host takes the entire store offline with no error message visible to administrators.
Pros and Cons of Environment Variables
FAQ
1. What is the difference between config.php and env.php?
config.php stores shared configuration like module lists, theme assignments, and non-sensitive settings. It belongs in version control. env.php stores environment-specific and sensitive data like database credentials, cache backends, and encryption keys. It must stay out of Git.
2. How do I override a Magento config value with an environment variable?
Use the CONFIG__ prefix format. Replace slashes in the config path with double underscores and uppercase everything. For example, web/secure/base_url becomes CONFIG__DEFAULT__WEB__SECURE__BASE_URL. Set this as an OS environment variable or in your server configuration.
3. Which deployment mode should I use for a live store?
Production mode. It pre-compiles static files, enables full caching, hides error messages from visitors, and delivers the best performance. Never run a live store in developer mode as it exposes stack traces and disables caching.
4. Does Magento 2.4.8 still support Elasticsearch?
Elasticsearch 8.17 remains supported for on-premises installations. However, OpenSearch 2 is the default search engine for Magento 2.4.8. Adobe Commerce Cloud no longer supports Elasticsearch. New installations should use OpenSearch.
5. How do I switch from file-based sessions to Redis?
Change the session node in env.php from 'save' => 'files' to 'save' => 'redis' and add the Redis connection details (host, port, database number). Use a different Redis database number than your cache configuration to prevent cache flushes from destroying sessions.
6. Can I use environment variables with Docker and Kubernetes?
Yes. Use getenv() calls in env.php to read values from container environment variables. Docker Compose and Kubernetes both support injecting environment variables at runtime, which makes the same env.php work across all environments without modification.
7. What happens if an environment variable is set wrong?
Magento fails silently for most env.php misconfigurations. A wrong database host shows a generic error page. A wrong Redis port falls back to file cache without warning. Always test configuration changes in staging before deploying to production.
8. How do I find the current value of a configuration setting?
Run bin/magento config:show followed by the config path. For example, bin/magento config:show web/secure/base_url. This command respects the full override hierarchy: database values, env.php, config.php, and OS environment variables.
Summary
Magento 2 environment variables live in app/etc/env.php and control database connections, cache backends, session storage, search engines, encryption, and deployment modes. The CONFIG__ prefix convention lets you override any configuration value through OS environment variables without touching code.
For Magento 2.4.8, configure your stack with PHP 8.3 or 8.4, MySQL 8.4 or MariaDB 11.4, OpenSearch 2, and Redis 7.2 or Valkey 8. Keep env.php out of version control, use separate configurations per environment, and test every change in staging first.
