I have just started a new Symfony 5 project (only worked on Symfony 3 before) and I am having a hard time to understand how values in .env
and .env.local
work together.
The Symfony docs say, that values in .env.local
will override values from .env
:
If you need to override an environment value (e.g. to a different
value on your local machine), you can do that in a .env.local file:
All machines I am working on use the same basic setup (same DB server, etc.) but some values are different (DB name, password, etc.). Thus I wanted to put the common configuration in .env
and the device specific values in .env.local
:
# .env
...
DB_SERVER="localhost"
DB_VERSION="10.4"
DB_USER=${DB_DBNAME}
DATABASE_URL="mysql://${DB_USER}:${DB_PASS}@${DB_SERVER}/${DB_DBNAME}?serverVersion=${DB_VERSION}"
# .env.local
DB_DBNAME="someDB"
DB_PASS="secretPW"
When using this setup I get an error and php bin/console debug:container --env-vars
shows DATABASE_URL "mysql://:@localhost/?serverVersion=10.4"
. Obviously DATABASE_URL
is build ignoring the values from .env.local
.
I can easily solve this by moving DATABASE_URL="mysql://...
to .env.local
but is this the intended way of using .env
and .env.local
?
I thought values of these files are merged where .env.local
values override .env
values. Is this not the case? Or did I make some error?
My Answer:
In Symfony, the environment variables are typically defined in the .env file, which is loaded by default. The .env.local file is used to override values from the .env file for local development or machine-specific configurations. The order of precedence for environment variables is as follows:
1. .env.local - This file is used to override values from the .env file for local development or machine-specific configurations.
2. .env - This file contains the default environment variables for the project.
3. .env.test - This file is used for testing environments.
4. .env.prod - This file is used for production environments.
In your case, you can put the common configuration values in the .env file and the device-specific values in the .env.local file. The values in the .env.local file will override the values from the .env file when the application is running in a local environment.
Rate this post
5 of 5 based on 2682 votesComments