I have 3 containers for a project: nginx, mongodb and nextjs.
Some variables are mutual for nginx and nextjs, other variables are mutual for mongodb and nextjs.
I have three different strategies for storing environment variables.
1. Storing all env variables in .env
I can store all my env vars inside the roots .env
where my docker-compose.yml
is stored. Docker will automatically include all the env variables after I run docker compose
for my project.
All the variables will be available on the host and in each container.
2. Separate .env
for each container
In this case all my env vars are isolated inside a container.
for mongodb:
env_vars:
- ./mongodb/.env
for nextjs:
env_vars:
- ./nextjs/.env
etc
No exposure for the host but repeated env vars between .env
files.
3. One .env
file and setting env vars in docker-compose.yml
I can set env variables from `environment
for mongodb:
environment:
- MONGO_URI=${MONGO_URI}
for nextjs:
environment:
- NEXTJS_HOST=${NEXTJS_HOST}
- NEXTJS_MONGO_URI=${MONGO_URI}
etc
All env vars are set in the host. No need to repeat yourself. Only one file for all containers.
4. General .env
and separate container based .env
s
General env variables in .env
in the root. And more particular envs in the container’s .env
file.
For example:
env_file:
- ./nextjs/.env
- ./.env
My approach is fourth. But it feels that I need to switch to another approach as it is getting to cluttered and hard to maintain. I want to move to the first approach.
What is the best practice from security point of view? From convenience point of view?