Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using multiple .env files bad practice?

I need to run tests in different environments : DEV, STAGING, PRODUCTION. And needless to say, the environment variables/secrets for the above environments would obviously be different.

I quick solution would be to have an env file for each environment like dev.env, staging.env & prod.env

But according to the docs of popular dotEnv npm package and 12 Factor app, it is not recommended to have multiple .env files in your repo.

Please give me a practical solution of managing env vars for multiple environments.

  • https://github.com/motdotla/dotenv#should-i-have-multiple-env-files
  • https://12factor.net/config
like image 730
abdp Avatar asked May 22 '26 09:05

abdp


2 Answers

If I understand correctly what they're writing here:

Should I have multiple .env files?

No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.

This doesn't mean that you shouldn't have multiple env files, but rather that you shouldn't have one main.env file with all the default configuration and additional env files (one per environment) that inherit from main.env and override certain values.

The reason why it's not recommended is that with such a configuration, it's difficult to understand "where a specific value is coming from?" (from which one of the following: main-env-file, specific-env-file, env-variable, code-default and etc).

That said, if you create multiple env files without a "main", this means that you'll need to duplicate many of the values across the different env files, which is better due to explicitness, but has the downside of duplication/verbosity.

Configuration is not trivial; when your project is small, it doesn't matter much how you choose to implement it. Still, if we're talking about something more critical like a company's product, then there are many solutions available out there, some are open-source and free, some cost money, but it's worth doing your research and figuring out which one provides you the benefits that are more meaningful to your use case.

Some of the more popular tools are: Puppet, Ansible, and Chef.

like image 168
Nir Alfasi Avatar answered May 24 '26 21:05

Nir Alfasi


In my opinion, it's better to have multiple .env in your project.

For example in Symfony, we can configure multiple environment for our project, example: local, dev, prod. it's purpose is to have a more clean and readable code.

I'm not sure about over technologies but you can read a little bit about .env in this Symfony article(no need to be a crack in symfony): https://symfony.com/doc/current/configuration.html#config-dot-env

like image 32
Newbie_dev Avatar answered May 24 '26 21:05

Newbie_dev